javascript 如何禁用鼠标滚轮单击按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11392318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:01:53  来源:igfitidea点击:

How to Disable the Mouse wheel click Button?

javascriptjquerymousewheel

提问by Déjà Bond

I'm trying to find a way of disabling the default action of the mouse wheel button which is to open the link in a new tab.

我试图找到一种禁用鼠标滚轮按钮默认操作的方法,即在新选项卡中打开链接。

Is that possible?

那可能吗?

回答by J.P. ten Berge

Bind a generic click event handler that specifically checks for middle clicks. Within that event handler, call e.preventDefault():

绑定一个专门检查中间点击的通用点击事件处理程序。在该事件处理程序中,调用e.preventDefault()

$("#foo").on('click', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
   }
});

Note that not all browsers support preventing this default action. For me, it only works in Chrome. Firefox, Opera and IE9 all do not raise the click event with middle mouse click. They do raise mouseup and mousedown.

请注意,并非所有浏览器都支持阻止此默认操作。对我来说,它只适用于 Chrome。Firefox、Opera 和 IE9 都不会通过鼠标中键单击引发单击事件。他们确实提高了 mouseup 和 mousedown。

回答by A.T.

This works for me...

这对我有用...

$(document).on("mousedown", "selector", function (ev) {
    if (ev.which == 2) {
        ev.preventDefault();
        alert("middle button");
        return false;
    }
});

回答by Gaurav Agrawal

Disable mouse wheel event by using JAVASCRIPT:

使用 JAVASCRIPT 禁用鼠标滚轮事件

In IE:

IE 中

document.attachEvent('onmousewheel', function(e){
     if (!e) var e = window.event;
     e.returnValue = false;
     e.cancelBubble = true;
     return false;
}, false);

In Safari:

Safari 中

document.addEventListener('mousewheel', function(e){
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}, false);

In Opera:

歌剧中

document.attachEvent('mousewheel', function(e){
    if (!e) var e = window.event;
    e.returnValue = false;
    e.cancelBubble = true;
    return false;
}, false);

In Firefox:

Firefox 中

document.addEventListener('DOMMouseScroll', function(e){
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}, false);

回答by Alexander Olehnovich

My code:

我的代码:

$(document).on('auxclick', 'a', function(e) {
if (e.which === 2) { //middle Click
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    return false;
}
return true;