20181213

oncontextmenu鼠标右键事件,阻止默认右键菜单

<div oncontextmenu="f();return false;"></div>

或者

<div oncontextmenu="return f()"></div>
<script>
    function f() {
        console.log(123);
        return false;
    }
</script>

或者

<div></div>
<script>
    var div = document.querySelector('div');
    div.oncontextmenu = function () {
        console.log(123);
        return false;
    }
</script>

原理都是通过给事件返回false来阻止默认行为,只是方式不一样
e.preventDefault()在元素有默认行为前提下阻止其默认行为
原生js的return false只能阻止默认行为,而jquery方法中的return false既能阻止默认行为又能阻止冒泡


阻止事件冒泡
标准浏览器:e.stopPropagation()
ie9之前:window.event.canceBubble = true
window.event和e都是事件参数对象,只不过一个是IE标准,一个是火狐的标准,事件参数e在IE8浏览器中不存在,此时用window.event代替
兼容代码

e = e || window.event;
if(e.stopPropagation){
    e.stopPropagation(); //IE9+
}else{ //IE678
    e.cancelBubble = true;
}



资料参考
js 阻止事件冒泡和默认行为 preventDefault、stopPropagation、return false

猜你喜欢

转载自www.cnblogs.com/Grani/p/10112360.html
今日推荐