How to differentiate between 'right click usin

2019-07-14 14:30发布

问题:

How do I differentiate between right click using mouse and context menu key press on a physical keyboard?

Using this code I tried printing event in console

$('#'+inputId).bind('contextmenu', function(e) {
    console.log(e);
});

I grabbed some output for the above code-

For right click using the mouse it is-

  1. button: 2
  2. originalEvent: MouseEvent
  3. type: "contextmenu"
  4. which: 3

For context menu key press on the keyboard it is-

  1. button: 2
  2. originalEvent: MouseEvent
  3. type: "contextmenu"
  4. which: 3

I want to perform some action only when 'context menu key' is pressed on the physical keyboard. How do I achieve that?

回答1:

Hiya there This will help you to capture the difference: Working Demo http://jsfiddle.net/pPnME/1/

I have tested this on Alienware - Chrome, when you will right click you will see the right click alert other wise on keyboard you will see keyborad alert.

Please note: you can identify the click based on which property: http://api.jquery.com/event.which/

For key or mouse events, this property indicates the specific key or button that was pressed.

Hope this fits the cause. :)

Also note there are few plugins available to get the shortcut but I would recommend stick to the basic and use the demo I have given if its only to capture both event separately rest demo is all your to play :)

code

/*
  1 = Left   Mousebutton
  2 = Centre Mousebutton
  3 = Right  Mousebutton
*/
$('input').mousedown(function(e) {
    if (e.which === 3) {
        alert('rightclick'); /* Right Mousebutton was clicked! */
    }
});
$('input').bind('contextmenu', function(e) {
    alert('keyboard yeah');
    //console.log(e);
});​


回答2:

you can check also if a key is pressed keyPressed is the event.

if no, is mouse event, if yes is contextmenu key

Edit: the keycode for contextMenu is 93