Detecting middle mouse click event jQuery

狂风中的少年 提交于 2019-11-28 07:20:48

问题


I want to show a jQuery-UI dialog box as a popup when user clicks on left mouse button or the middle one. It works for left click (I get the alert box and after that the popup) but doesn't work for middle (neither alert box nor popup). What am I missing?

$('a.external').live('click', function(e){
  if( e.which <= 2 ) {
    e.preventDefault();
    alert ("inside if");
  }
  popUp.start(this);
});

回答1:


Use mousedown or mouseup instead of click. And (unless you are using a very old version of jQuery) use .on() instead of .live():

$(document).on("mousedown", "a.external", function(e) {
   if( e.which <= 2 ) {
      e.preventDefault();
      alert ("inside if");
   }
   popUp.start(this);
});

...where ideally you'd use a parent element much closer to the link than document.

Demo: http://jsfiddle.net/7S2SQ/




回答2:


To get this working fully in Firefox (40.0.3), I had to implement .on('mouseup', fn), as follows:

$(selector).on('mouseup', function (e) {

    switch (e.which)
    {
        // Left Click.
        case 1:
            // By way of example, I've added Ctrl+Click Modifiers.
            if (e.ctrlKey) {
                // Ctrl+LeftClick behaviour.
            } else {
                // Standard LeftClick behaviour.
            }
            break;

        // Middle click.
        case 2:
            // Interrupts "Firefox Open New Tab" behaviour.
            break;

        // Default behaviour for right click.
        case 3:
            return;
    }

    // Pass control back to default handler.
    return true;
});


来源:https://stackoverflow.com/questions/17130852/detecting-middle-mouse-click-event-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!