How to distinguish between left and right mouse click with jQuery

后端 未结 17 2721
独厮守ぢ
独厮守ぢ 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: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;
    }
    
    

提交回复
热议问题