js去掉浏览器右键点击默认事件(+vue项目开启右键行为)

js去掉浏览器右键点击默认事件

1、阻止整个页面所有的右击事件

document.oncontextmenu = function(){
  return false;
}

2、特定的区域/元素

document.getElementById("test").oncontextmenu = function(e){
  return false;
}

3、去掉以后给需要的区块加特定的事件

js:

document.getElementById("test").onmousedown = function(e){
  if(e.button ==2){
    alert("你点了右键");
  }else if(e.button ==0){
    alert("你点了左键");
  }else if(e.button ==1){
    alert("你点了滚轮");
  }
}

jq:

$("#test").mousedown(function(e){
  //doing
});

4、通过jq bind绑定和触发

$('').bind("contextmenu",function (e){

   //doning

   return false;

});

$('').trigger('contextmenu');

Vue-阻止事件冒泡-开启右键-键盘类事件

1、阻止事件冒泡

  当点击按钮时,会触发button的click也会触发父级的方法

<div id="box">
     <div @click="parentShow">
        <button type="button" @click="show()">按钮</button>
     </div>
</div>

解决方法:

  第一种方法,传入一个event对象,然后对象里有cancelBubble方法,设置为true

<div id="box">
     <div @click="parentShow">
          <button type="button" @click="show($event)">按钮</button>
     </div>
</div>
methods: {
     show: function(ev){
          alert(1);
          ev.cancelBubble = true;
     },
     parentShow: function(){
          alert(2);
     }
}

  第二种方法是vue封装好的,直接在click的后面加上.stop,建议使用

<div id="box">
     <div @click="parentShow">
           <button type="button" @click.stop="show()">按钮</button>
     </div>
</div>

2、阻止左键,开启右键行为

  按钮的右键行为,vue事件。这里的prevent是关闭默认行为,相当于 传个$event 然后 event.preventDefault()

<button type="button" @contextmenu.prevent="show1()">按钮</button>

3、键盘类事件

  keyup、keydown是监听键盘按下,弹起事件,后面的.enter是指定键盘的按键,比如常见的:up、down、left、right、enter、tab等

<input type="text" @keyup.enter="show2()" />

  也可以通过$event的keyCode来获取键盘的值。比如:

<input type="text" @keydown="show2($event)" />
show2: function(ev){
       console.log(ev.keyCode);
}

参考文章:https://www.cnblogs.com/zycbloger/p/5643122.html

原文地址:https://www.cnblogs.com/rachelch/p/8135883.html