How to distinguish between left and right mouse click with jQuery

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

    As of jQuery version 1.1.3, event.which normalizes event.keyCode and event.charCode so you don't have to worry about browser compatibility issues. Documentation on event.which

    event.which will give 1, 2 or 3 for left, middle and right mouse buttons respectively so:

    $('#element').mousedown(function(event) {
        switch (event.which) {
            case 1:
                alert('Left Mouse button pressed.');
                break;
            case 2:
                alert('Middle Mouse button pressed.');
                break;
            case 3:
                alert('Right Mouse button pressed.');
                break;
            default:
                alert('You have a strange Mouse!');
        }
    });
    

提交回复
热议问题