【问题标题】:How to disable mouse middle button click to open in a new tab or new window如何禁用鼠标中键单击以在新选项卡或新窗口中打开
【发布时间】:2017-06-28 09:02:52
【问题描述】:

我正在尝试禁用鼠标的右键和中键,以便在单击任何菜单或超链接时无法打开新窗口或选项卡。下面的 javascript 代码适用于右键,但不适用于中键。鼠标中键被捕获,但单击超链接或菜单时仍会打开新窗口或选项卡。

<script type="text/javascript">
    if (document.layers) {           
        document.captureEvents(Event.MOUSEDOWN);
        document.onmousedown = function () {
            return false;
        };
    }
    else {
        document.onmouseup = function (e) {
            if (e != null && e.type == "mouseup") {      

                if (e.which == 3) {
                    alert("Sorry..... Right click Is Disabled!!!!");                        
                        return false;
                }

                if(e.which===2)
                {
                   e.preventDefault();
                    e.stopImmediatePropagation();
                    alert("Sorry..... Mouse Scroll click Is Disabled!!!!");
                    return false;
                }
                else if(e.button===4)
                {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    alert("Sorry..... Mouse Scroll click Is Disabled!!!!");
                    return false;
                }
            }
        };
    }

它不适用于 firefox、chrome 和 IE。

【问题讨论】:

  • 您是否还禁用“正常”左键单击? Middle click = ctrl left click(或 shift left click,取决于浏览器)
  • 这个问题并不完全重复,但这个答案肯定会有所帮助:stackoverflow.com/a/28354454/178551

标签: javascript jquery html mouseevent mousewheel


【解决方案1】:

试试

document.onmousedown= function (e) {
    if( e.which == 2 ) {
        e.preventDefault();
        alert("middle button"); 
    }
}

【讨论】:

  • 感谢您的回复@Durgesh。但它不起作用。
  • @KishorKulkarni 我已经更新了答案请查看
【解决方案2】:

根据MDNauxclick 事件处理“使用鼠标中键在新选项卡中打开链接”行为。

以下代码将阻止整个页面的中间点击行为。

window.addEventListener("auxclick", (event) => {
  if (event.button === 1) event.preventDefault();
});

如果您只想对某个链接禁用它,只需将事件侦听器目标(窗口)替换为对特定节点的引用即可。

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多