How to distinguish between left and right mouse click with jQuery

后端 未结 17 2676
独厮守ぢ
独厮守ぢ 2020-11-21 22:36

How do you obtain the clicked mouse button using jQuery?

$(\'div\').bind(\'click\', function(){
    alert(\'clicked\');
});

this is trigger

相关标签:
17条回答
  • 2020-11-21 23:03

    there is also a way, to do it without JQuery!

    check out this:

    document.addEventListener("mousedown", function(evt) {
        switch(evt.buttons) {
          case 1: // left mouse
          case 2: // right mouse
          case 3: // middle mouse <- I didn't tested that, I just got a touchpad
        }
    });
    
    0 讨论(0)
  • 2020-11-21 23:07

    $("#element").live('click', function(e) {
      if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
           alert("Left Button");
        }
        else if(e.button == 2){
           alert("Right Button");
        }
    });
    

    Update for the current state of the things:

    var $log = $("div.log");
    $("div.target").on("mousedown", function() {
      $log.text("Which: " + event.which);
      if (event.which === 1) {
        $(this).removeClass("right middle").addClass("left");
      } else if (event.which === 2) {
        $(this).removeClass("left right").addClass("middle");
      } else if (event.which === 3) {
        $(this).removeClass("left middle").addClass("right");
      }
    });
    div.target {
      border: 1px solid blue;
      height: 100px;
      width: 100px;
    }
    
    div.target.left {
      background-color: #0faf3d;
    }
    
    div.target.right {
      background-color: #f093df;
    }
    
    div.target.middle {
      background-color: #00afd3;
    }
    
    div.log {
      text-align: left;
      color: #f00;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="target"></div>
    <div class="log"></div>

    0 讨论(0)
  • 2020-11-21 23:07
        $.event.special.rightclick = {
         bindType: "contextmenu",
            delegateType: "contextmenu"
          };
    
       $(document).on("rightclick", "div", function() {
       console.log("hello");
        return false;
        });
    
    0 讨论(0)
  • 2020-11-21 23:08
    $.event.special.rightclick = {
        bindType: "contextmenu",
        delegateType: "contextmenu"
    };
    
    $(document).on("rightclick", "div", function() {
        console.log("hello");
        return false;
    });
    

    http://jsfiddle.net/SRX3y/8/

    0 讨论(0)
  • 2020-11-21 23:08

    With jquery you can use event object type

    jQuery(".element").on("click contextmenu", function(e){
       if(e.type == "contextmenu") {
           alert("Right click");
       }
    });
    
    0 讨论(0)
提交回复
热议问题