jQuery key code for command key

白昼怎懂夜的黑 提交于 2019-11-27 03:33:25

jQuery already handles that. To check if control was pressed you should use:

$(window).keydown(function (e){
    if (e.ctrlKey) alert("control");
});

The list of modifier keys:

e.ctrlKey
e.altKey
e.shiftKey

And as fudgey suggested:

e.metaKey

Might work on MAC. Some other ways here as well.

If you're not interested in the the exact moment the Command key is pressed, just whether it is pressed when another key is pressed, then you can use the metaKey property of the event.

Otherwise, for keydown and keyup events, the property you need is keyCode in all browsers. Unfortunately, the Command key does not have the same key code in all browsers, and the left and right Commands have different values in WebKit (91 and 93 respectively). I can't see an easy way of detecting these keys without some kind of browser sniff, but there may be one. The which property definitely won't help you.

For more information, http://unixpapa.com/js/key.html has comprehensive coverage of key event handling in all the major browsers.

Here you go, try this live in this runnable code snippet:

$(window).on('keypress', function(event) {
  $("body").append($("<p>").text(
       "ctrlKey " + event.ctrlKey
    + "; altKey " + event.altKey
    + "; metaKey " + event.metaKey
    + "; shiftKey " + event.shiftKey
    + "; isCommandPressed " + isCommandPressed(event)
  ));
  
});

function isCommandPressed(event) {
  return event.metaKey && ! event.ctrlKey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Focus on this select control and try pressing keys:</p>

<p><select><option>Test</option></select></p>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!