如何在Javascript中同时按下三个键盘时触发事件
我正在编写代码,以便在按下 ctrl + shift + z
键时执行特定功能。当我同时按两个键时,它工作正常,但当我按三个键时,该事件不会发生。下面是我写的代码。
try1:
document.onkeydown = function (e) {
if (e.ctrlKey && e.key === 'z') { // It works
undo() // ctrl+ z
}
else if (e.ctrlKey && e.shiftKey && e.key==='z' ) { //It doesn't work
redo(); //ctrl + shift + z
}
}
try2:
document.onkeydown = function (e) { //
var ctrl, shift,z
console.log(e.key)
switch (e.key) {
case 'Control':
ctrl = true;
break;
case 'Shift':
shift = true;
break;
case 'Z':
z = true;
break;
}
if (ctrl&&shift&&z) redo()
}
如果您在三个键盘上打字,这些都不起作用。
如何使其在按下 ctrl+shift+z
时起作用
I'm writing code to execute a specific function when the ctrl + shift + z
key is pressed. When I press two keys at the same time, it works fine, but when I press three keys, the event does not occur. Below is the code I wrote.
try1:
document.onkeydown = function (e) {
if (e.ctrlKey && e.key === 'z') { // It works
undo() // ctrl+ z
}
else if (e.ctrlKey && e.shiftKey && e.key==='z' ) { //It doesn't work
redo(); //ctrl + shift + z
}
}
try2:
document.onkeydown = function (e) { //
var ctrl, shift,z
console.log(e.key)
switch (e.key) {
case 'Control':
ctrl = true;
break;
case 'Shift':
shift = true;
break;
case 'Z':
z = true;
break;
}
if (ctrl&&shift&&z) redo()
}
Neither of these will work if you're typing on three keyboards.
How to make it work when ctrl+shift+z
is pressed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改条件的顺序,因为第一个条件始终是
true
如果第二个条件为true
,则导致第二个条件永远不会执行的代码。Change the order of the conditions, as the first condition is always
true
if the second istrue
, causing the code for the second condition to never execute.我很好地跟踪按键的方法是一个对象:
I nice way to keep track of pressed keys is with an object: