How to distinguish between left and right mouse click with jQuery

后端 未结 17 2720
独厮守ぢ
独厮守ぢ 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 22:58

    event.which === 1 ensures it's a left-click (when using jQuery).

    But you should also think about modifier keys: ctrlcmdshiftalt

    If you're only interested in catching simple, unmodified left-clicks, you can do something like this:

    var isSimpleClick = function (event) {
      return !(
        event.which !== 1 || // not a left click
        event.metaKey ||     // "open link in new tab" (mac)
        event.ctrlKey ||     // "open link in new tab" (windows/linux)
        event.shiftKey ||    // "open link in new window"
        event.altKey         // "save link as"
      );
    };
    
    $('a').on('click', function (event) {
      if (isSimpleClick(event)) {
        event.preventDefault();
        // do something...
      }
    });
    

提交回复
热议问题