Bind Multiple Keys to Keypress Event(将多个键绑定到 Keypress 事件)
问题描述
我目前正在使用这个 Javascript 按键代码在按键时触发事件:
I am currently using this Javascript keypress code to fire events upon keypress:
$(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;
}
});
推荐答案
如果你想一次检查多个键,你应该只使用一个常规键和一个或多个修饰键(alt/shift/ctrl),因为你不能确保在用户的键盘上实际上可以同时按下两个常规键(实际上,它们总是可以按下,但由于键盘的接线方式,PC 可能无法理解).
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).
您可以使用 e.altKey、e.ctrlKey、e.shiftKey 字段来检查是否按下了匹配的修饰键.
You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.
例子:
$(document).keydown(function(e) {
if(e.which == 98 && e.ctrlKey) {
// ctrl+b pressed
}
});
这篇关于将多个键绑定到 Keypress 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将多个键绑定到 Keypress 事件


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01