javascript 将多个键绑定到 Keypress 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4173460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind Multiple Keys to Keypress Event
提问by mcbeav
I am currently using this Javascript kepypress code to fire events upon keypress:
我目前正在使用这个 Javascript kepypress 代码在按键时触发事件:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
but what i am wondering is if i can instead of binding one key bind a combination of two keys. Could I possibly do something like:
但我想知道的是,我是否可以不绑定一个键来绑定两个键的组合。我可能会做这样的事情:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39 && 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
回答by ThiefMaster
If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).
如果你想一次检查多个键,你应该只使用一个普通键和一个或多个修饰键(alt/shift/ctrl),因为你不能确定用户键盘上的两个普通键实际上可以同时按下(实际上,它们总是可以被按下,但由于键盘的接线方式,PC 可能无法理解)。
You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.
您可以使用 e.altKey、e.ctrlKey、e.shiftKey 字段来检查是否按下了匹配的修饰键。
Example:
例子:
$(document).keydown(function(e) {
if(e.which == 98 && e.ctrlKey) {
// ctrl+b pressed
}
});
回答by lonesomeday
Why not use ifrather than switch?
为什么不使用if而不是switch?
$(document).keydown(function(e) {
if ((e.keyCode === 37) || (e.keyCode === 39)) {
e.preventDefault();
alert("Arrow Key");
}
});
回答by ThiefMaster
You can use the case fallthrough:
您可以使用案例失败:
$(document).keydown(function(e) {
switch(e.which) {
case 39:
case 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
Note that I'm using e.whichinstead of e.keyCodeto make it work in all browsers (jQuery automatically assigns the property which actually contains the key code to e.which).
请注意,我使用e.which而不是e.keyCode使其在所有浏览器中工作(jQuery 自动将实际包含键代码的属性分配给 e.which)。

