How to distinguish between left and right mouse click with jQuery

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

    There are a lot of very good answers, but I just want to touch on one major difference between IE9 and IE < 9 when using event.button.

    According to the old Microsoft specification for event.button the codes differ from the ones used by W3C. W3C considers only 3 cases:

    1. Left mouse button is clicked - event.button === 1
    2. Right mouse button is clicked - event.button === 3
    3. Middle mouse button is clicked - event.button === 2

    In older Internet Explorers however Microsoft are flipping a bit for the pressed button and there are 8 cases:

    1. No button is clicked - event.button === 0 or 000
    2. Left button is clicked - event.button === 1 or 001
    3. Right button is clicked - event.button === 2 or 010
    4. Left and right buttons are clicked - event.button === 3 or 011
    5. Middle button is clicked - event.button === 4 or 100
    6. Middle and left buttons are clicked - event.button === 5 or 101
    7. Middle and right buttons are clicked - event.button === 6 or 110
    8. All 3 buttons are clicked - event.button === 7 or 111

    Despite the fact that this is theoretically how it should work, no Internet Explorer has ever supported the cases of two or three buttons simultaneously pressed. I am mentioning it because the W3C standard cannot even theoretically support this.

提交回复
热议问题