命令键的 jQuery 键代码
我已阅读 jQuery 事件按键:按下了哪个键? 和 < a href="https://stackoverflow.com/questions/2445613/how-can-i-check-if-key-is-pressed-during-click-event-with-jquery">我如何检查键是否为在使用 jquery 的点击事件期间按下?
但是我的问题是您是否可以为所有浏览器获取相同的按键事件?目前我知道 Firefox 为 command 按钮 (Mac) 提供了代码 224,而 Chrome 和 Safari 为它提供了值 91。这是简单检查用户正在使用的浏览器并根据按下的键的最佳方法或者有没有办法让我可以在所有浏览器上获得 1 个关键代码? 注意我得到的值是:
var code = (evt.keyCode ? evt.keyCode : evt.which);
如果可能的话,我希望不使用插件,因为我只需要了解 command/ctrl (Windows 系统)键按下。
I have read jQuery Event Keypress: Which key was pressed? and How can i check if key is pressed during click event with jquery?
However my question is if you can get the same key event for all browsers? Currently I know that Firefox gives the command button (Mac) the code 224 while Chrome and Safari give it the value 91. Is the best approach to simply check what browser the user is using and base the key pressed on that or is there a way so that I can get 1 key code across all browsers?
Note I am getting the value with the:
var code = (evt.keyCode ? evt.keyCode : evt.which);
I would love to not use a plugin if possible just because I only need to know about the command/ctrl (windows system) key pressed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jQuery 已经处理了这个问题。要检查是否按下了控件,您应该使用:
修饰键列表:
正如软糖建议的那样:
可能适用于 MAC。这里还有一些其他方法。
jQuery already handles that. To check if control was pressed you should use:
The list of modifier keys:
And as fudgey suggested:
Might work on MAC. Some other ways here as well.
如果您对按下 Command 键的确切时间不感兴趣,只对按下另一个键时是否按下该键感兴趣,那么您可以使用
metaKey
属性事件。否则,对于
keydown
和keyup
事件,您需要的属性在所有浏览器中都是keyCode
。不幸的是,Command 键在所有浏览器中并不具有相同的键码,并且左右 Command 在 WebKit 中具有不同的值(分别为 91 和 93)。如果没有某种浏览器嗅探,我看不到一种简单的方法来检测这些键,但可能有一种。which
属性绝对不会帮助你。有关更多信息,http://unixpapa.com/js/key.html 全面介绍了所有关键事件处理主要浏览器。
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
andkeyup
events, the property you need iskeyCode
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. Thewhich
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: