How to distinguish between left and right mouse click with jQuery

后端 未结 17 2722
独厮守ぢ
独厮守ぢ 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:44

    You can also bind to contextmenu and return false:

    $('selector').bind('contextmenu', function(e){
        e.preventDefault();
        //code
        return false;
    });
    

    Demo: http://jsfiddle.net/maniator/WS9S2/

    Or you can make a quick plugin that does the same:

    (function( $ ) {
      $.fn.rightClick = function(method) {
    
        $(this).bind('contextmenu rightclick', function(e){
            e.preventDefault();
            method();
            return false;
        });
    
      };
    })( jQuery );
    

    Demo: http://jsfiddle.net/maniator/WS9S2/2/


    Using .on(...) jQuery >= 1.7:

    $(document).on("contextmenu", "selector", function(e){
        e.preventDefault();
        //code
        return false;
    });  //does not have to use `document`, it could be any container element.
    

    Demo: http://jsfiddle.net/maniator/WS9S2/283/

提交回复
热议问题