How does one capture a Mac's Cmd key via JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Here is how I did it in AngularJS
You can also look at the
event.metaKey
attribute on the event if you are working with keydown events. Worked wonderfully for me! You can try it here.Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js
Just use it like this, e.g.:
Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.
For people using jQuery, there is an excellent plugin for handling key events:
jQuery hotkeys on GitHub
For capturing ⌘+S and Ctrl+S I'm using this:
Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on
keydown
/keyup
and record when a key is pressed and then depressed based onevent.keyCode
.Unfortunately, these key codes are browser-dependent:
224
17
91
(Left Command) or93
(Right Command)You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ⌘+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
When pressing x on it's own, this will output
120, false
. When pressing ⌘+x, it will output120, true
This only seems to work in Safari - not Chrome