是否可以通过用户脚本Jquery识别所有键码事件 [英] Can all keycode events be recognized by a user-script Jquery
问题描述
我正在使用 Tampermonkey 构建一个用于识别键码事件的用户脚本,当键被触发时,它将执行一项功能。
I am building a userscript with Tampermonkey that recognizes keycode events and when the key is fired it will do a function.
例如。我想按 Enter ,其键码
为13,所以我使用了这段代码
for eg. I want to press Enter and its keycode
is 13 so I used this code
$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
alert("You Pressed Enter key");
}
else if(which == '17'){
alert("You Pressed Control key");
}
});
代码与 Enter 并且 1 但不能与 Ctrl 或 Shift 和其他键一起使用。
The code works fine with Enter and with 1 but doesn't work with Ctrl nor Shift and other keys.
我有什么事吗丢失或不是所有关键事件都可以处理?
Is there any thing I am missing or not all key events can be handled?
注意:我一直在使用此链接获取我的密钥代码并在我的脚本中使用它们。
NOTE : I have been using this link to get my keycodes and using them in my script.
推荐答案
keypress
未触发控制键。根据Mozilla文档的说明:
keypress
isn't triggered for control key. Per the description on Mozilla docs:
键时触发
keypress
事件按下会产生一个字符值。产生字符值的键的示例是字母,数字和标点符号键。不产生字符值的键的示例是修饰键,例如 Alt , Shift , Ctrl 或 Meta 。
The
keypress
event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.
一种方法是收听 keydown
或 keyup
事件:
One way to get around is to listen to keydown
or keyup
event:
$(document).keydown(function(event) {
var which = (event.which ? event.which : event.keyCode);
if (which == '13') {
alert("You Pressed Enter key");
} else if (which == '17') {
alert("You Pressed Control key");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于是否可以通过用户脚本Jquery识别所有键码事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!