使用 jQuery 检测中间按钮单击(滚动按钮)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5392442/
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-08-26 19:05:37  来源:igfitidea点击:

Detect middle button click (scroll button) with jQuery

jquerybuttonclickscroll

提问by Codebeat

I have a list with a tags to play some mp3 files onclick. It is working fine when binding on the 'click' event with jQuery:

我有一个带有标签的列表,可以在单击时播放一些 mp3 文件。使用 jQuery 绑定“click”事件时它工作正常:

$oo.data({'__mp3play':true,'wapiHandle':h+0,'wapiIndex':o.ajaxPlayList[h].length})
           .bind( 'click', function()
            { var wh = $j(this).data('wapiHandle');
              if( typeof o.regObjects[wh] == 'object' && o.regObjects[wh].play(this.href))
               { return false; }
            });

When clicking the left mouse button: It disables default handling when my flash plugin is loaded otherwise it will be opened normally.

单击鼠标左键时:加载我的 Flash 插件时禁用默认处理,否则它将正常打开。

BUT: When I use the scrollbutton of the mouse and click on it, the click event will not fired and the link opens normally.

但是:当我使用鼠标的滚动按钮并单击它时,不会触发单击事件并且链接正常打开。

I have tried to use mousedown or mouseup events but doesn't help, the link always opens normally with the side effect that the music starts playing also with the flash player.

我曾尝试使用 mousedown 或 mouseup 事件,但没有帮助,链接总是正常打开,副作用是音乐也开始用 Flash 播放器播放。

Also preventDefault()does not work at all.

preventDefault()根本不起作用。

Can somebody tell me how to detect the middle mouse button click (scroll button click)?

有人能告诉我如何检测鼠标中键点击(滚动按钮点击)吗?

Thank you for your comments.

谢谢您的意见。

PS: I have already tried other solutions about the 'middle button' available on this site.

PS:我已经尝试过有关此站点上可用的“中间按钮”的其他解决方案。

Tested in all kind of browsers with the same result.

在各种浏览器中测试,结果相同。

EDIT: This also does not work, the link will be opened normally when using the middle mouse button. When using the left mouse button, nothing happen.

编辑:这也不起作用,使用鼠标中键时链接将正常打开。使用鼠标左键时,没有任何反应。

$oo.bind( 'mousedown click mouseup', function(e)
{ e.preventDefault(); e.stopPropagation(); return false; });

采纳答案by Codebeat

Okay guys,

好吧,伙计们,

Thank you for your input. '@no.good.at.coding' has a nice solution but does not work on IE (see later on this writing) but is a good starting point. I change his code to this:

谢谢您的意见。'@no.good.at.coding' 有一个很好的解决方案,但不适用于 IE(见下文),但它是一个很好的起点。我把他的代码改成这样:

// Avoid relations will be opened in extra tab when clicking middle-scroll-button to open it
$(document).bind($.browser.msie ? "mousedown" : "click", function(e)
{
    if (e.which == 2 && e.target.tagName == 'A') 
    {
        var bIE = $.browser.msie,
            $o = $(e.target),
            oe = $o.data('events'),
            b = true,
            f = function(){};

        if (typeof oe == 'object' && oe['click']) {
            f = function(){ $o.trigger('click'); }
        } else {
            b = (typeof $o[0].href == 'string' && ($o[0].target == undefined || $o[0].target == '' || $o[0].target == '_self'));
            if (b) { 
                f = function () { window.location.href=$o[0].href; };
            }
        }

        if (!b) { return; }

        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        if (bIE)
        {
            if (!window.__swcp__) { 
                window.__swcp__= $('<div style="position:fixed;top:0px;left:0px;width:100%;height:100%;background:#000;display:block;z-index:9999;opacity:0.01;filter:alpha(opacity:1);" />').appendTo('body'); 
            }
            window.__swcp__.show();
        }

        setTimeout(f, 50);
        if (bIE) { 
            setTimeout( function() { window.__swcp__.hide(); }, 1000 );
        }

        return false;
    }
});

The middle-button acts now like the left-button of a mouse. As you can see IE needs some more, we must unfocus the link tag for 1 second to avoid that it will be opened in an extra tab. I use here a simple way to do this, create a 'for the eye" transparent div (opacity = 0.01) that will be placed over the window content so any link on the page will be unfocused. The user will not notice any difference except that the mouse pointer can change from pointer to default and after one second it change back to pointer (IE only). I can live with that.

中键现在就像鼠标的左键一样。正如你所看到的 IE 需要更多,我们必须将链接标签移开 1 秒钟,以避免它会在额外的选项卡中打开。我在这里使用一个简单的方法来做到这一点,创建一个“for the eye”透明 div (opacity = 0.01) 将放置在窗口内容上,因此页面上的任何链接都不会被聚焦。用户不会注意到任何区别,除了鼠标指针可以从指针变为默认值,一秒后又变回指针(仅限 IE)。我可以接受。

I accept this as an answer, but if you have better idea's let me know.

我接受这个作为答案,但如果您有更好的想法,请告诉我。

回答by RobertPitt

Well after a quick test it seems that the three are ordered as follows:

好吧,经过快速测试,这三个似乎是按如下顺序排列的:

  • Left - 1
  • Middle - 2
  • Right - 3
  • 左 - 1
  • 中 - 2
  • 右 - 3

So if you had:

所以如果你有:

$(document).mousedown(function(e){
    switch(e.which)
    {
        case 1:
            //left Click
        break;
        case 2:
            //middle Click
        break;
        case 3:
            //right Click
        break;
    }
    return true;// to allow the browser to know that we handled it.
});

回答by KyleMit

Please don'tfire click actions during the mousedownevent. It ignores the rest of the event pipeline and goes against current user expectations and design practices.

不要mousedown活动期间触发点击操作。它忽略了事件管道的其余部分,违背了当前的用户期望和设计实践。

Problem

问题

Here's a look at the normal order of events that fire for each click type:

以下是针对每种点击类型触发的正常事件顺序:

$(document).on("mousedown mouseup click focus blur",function(e) {
  console.log("{" + e.which + ":" + e.type + "}"); 
});    

Click Events

点击事件

Typically, we handle the very last clickevent because it signifies the users final intent to proceed with the current action.

通常,我们处理最后一个click事件,因为它表示用户进行当前操作的最终意图。

The clickevent is fired when a pointing device button (usually a mouse's primary button) is pressed and releasedon a single element.

click当在单个元素按下并释放指针设备按钮(通常是鼠标的主按钮)时,将触发该事件。

Unfortunately, middle mouse presses do not fire such an event (probably because doing so would force developers listening to the click event to distinguish between multiple possible invocations). But if we want to wire up actions against the middle click, we should follow the same UX expectations.

不幸的是,鼠标中键不会触发这样的事件(可能是因为这样做会迫使开发人员监听点击事件以区分多个可能的调用)。但是,如果我们想针对中间点击进行操作,我们应该遵循相同的 UX 期望。

Solution

解决方案

We'll listen for mousedownevents and immediately attach a one time use handler for mouseupevents. If the middle key was pressed and if the elements match, we'll triggerour own custom eventwith type middleclick, which we'll seed from the original event.

我们将侦听mousedown事件并立即为事件附加一个一次性使用的处理程序mouseup。如果按下中间键并且元素匹配,我们将使用 type触发我们自己的自定义事件middleclick,我们将从原始事件中播种

$(document).on("mousedown", function (e1) {
  $(document).one("mouseup", function (e2) {
    if (e1.which == 2 && e1.target == e2.target) {
      var e3 = $.event.fix(e2);
      e3.type = "middleclick";
      $(e2.target).trigger(e3)
    }
  });
});

That'll help separate out determining ifthe middle button was clicked with how we we want to handle it in that case, so we can setup a listener for our custom event type like this:

这将帮助分离出来,确定是否中间的按钮被点击了我们如何,我们要处理它在这种情况下,所以我们可以设置我们的自定义事件类型这样的监听器:

$(document).on("middleclick", function (e) {
    console.log("{" + e.target.nodeName.toLowerCase() + ":" + e.type + "}"); 
});

Working Demo in jsFiddleand Stack Snippets:

jsFiddle和 Stack Snippets 中的工作演示:

$(document).on("mousedown", function (e1) {
  $(document).one("mouseup", function (e2) {
    if (e1.which == 2 && e1.target == e2.target) {
     var e3 = $.event.fix(e2);
      e3.type = "middleclick";
      $(e2.target).trigger(e3)
    }
  });
});

$(document).on("middleclick", function (e) {
  console.log("{" + e.target.nodeName.toLowerCase() + ":" + e.type + "}"); 
});

$(document).on("mousedown mouseup click focus blur",function(e) {
  console.log("{" + e.which + ":" + e.type + "}"); 
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

<div  style="background:#31965a;color:white;width:100px;height:100px;line-height:100px;text-align:center;">
  Click Me!
</div>

* Tested in Chrome, FF, Edge, & IE11

* 在 Chrome、FF、Edge 和 IE11 中测试

回答by no.good.at.coding

Ok, I think I've got it. Here's a fiddle that seems to work. The trick (at least with FF4) seems to be to bind a click handler to the documentand have it stop the propagation.

好的,我想我明白了。这是一个似乎有效小提琴。技巧(至少对于 FF4)似乎是将点击处理程序绑定到document并让它停止传播。

$(document).click(function(e){
        //not checking for the right click will prevent the context-menu from showing, you may or may not want to do that
        if (e.which != 3) { 
            e.preventDefault();
            return false;
        }
    });

This solution was found on this forum page.

这个解决方案是在这个论坛页面上找到的

回答by Yule

e.which should do it:

e.which 应该这样做:

Simple example:

简单的例子:

$(document).ready(function(){
    $(document).mousedown(function(e){
         alert(e.which); // ##=> left
    }) 
})

回答by Drupal Development Costa Rica

If you, (like me) found this because of weird-o middle click bugs from clients. And you just want any middle or right click to behave like a left click

如果你,(像我一样)发现这个是因为来自客户的奇怪的中间点击错误。并且您只希望任何中键或右键单击都表现得像左键单击

Forget all that lame code for IE.

忘记 IE 的所有蹩脚代码。

Short and sweet:

简短而甜蜜:

$(document).click(function(e){
  // checking for any non left click and convert to left click.
  if (e.which != 1) { 
    e.which = 1;
  }
});

Obviously if you need a little more discrimination, you can do something like:

显然,如果您需要更多的歧视,您可以执行以下操作:

$('a.no-non-left-clickies').click(function(e){
  // checking for any non left click and convert to left click.
  if (e.which != 1) { 
    e.which = 1;
  }
});