Jquery: detect if middle or right mouse button is clicked, if so, do this:

前端 未结 3 452
终归单人心
终归单人心 2020-11-30 10:39

Check out my jsfiddle demo, if e.which == 1 then when you left click the h2 it will e.which == 2 or e.which == 3 then it wont work. 2

相关标签:
3条回答
  • 2020-11-30 10:43

    Now button has been fouled up beyond all recognition. According to W3C its values should be:

    • Left button – 0
    • Middle button – 1
    • Right button – 2

    According to Microsoft its values should be:

    • Left button – 1
    • Middle button – 4
    • Right button – 2

    No doubt the Microsoft model is better than W3C’s. 0 should mean “no button pressed”, anything else is illogical.

    From http://www.quirksmode.org/js/events_properties.html

    0 讨论(0)
  • 2020-11-30 11:01

    I've noticed some oddities in the past with using the click event for anything but a regular left-click. I don't recall the details, but if you change "click" to "mousedown" or "mouseup" you should have better results.

    0 讨论(0)
  • 2020-11-30 11:07

    You may want to trap the mousedown event, and you also need to prevent the oncontextmenu event to stop the context menu from coming up during the right click event.

    $("h2").live('mousedown', function(e) { 
       if( (e.which == 1) ) {
         alert("left button");
       }if( (e.which == 3) ) {
         alert("right button");
       }else if( (e.which == 2) ) {
          alert("middle button"); 
       }
       e.preventDefault();
    }).live('contextmenu', function(e){
       e.preventDefault();
    });
    

    UPDATE: .live() has been deprecated since jQuery 1.9. Use .on() instead.

    $("h2").on('mousedown', function(e) { 
      if (e.which == 1) {
        alert("left button");
      } else if (e.which == 3) {
        alert("right button");
      } else if (e.which == 2) {
        alert("middle button");
      }
      e.preventDefault();
    });
    
    0 讨论(0)
提交回复
热议问题