同时检测到两个键盘按键被按下 [英] Detecting two keyboard keys being down at the same time
本文介绍了同时检测到两个键盘按键被按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用此代码来检测同时按下两个键盘箭头:
I tried with this code to detect two keyboard arrows being simultaneously pressed:
document.addEventListener('keydown', event => {
if (event.keyCode === 38) {
console.log('up Arrow')
}
if (event.keyCode === 39) {
console.log('right Arrow')
}
})
但这是行不通的,但是无论我多么努力尝试完全同时按下它们.
But it doesn't work, however hard I try to press them at exactly the same time.
如何彻底解决此问题并检测两个按键何时按下?
How can I cleanly fix this and detect when both keys are down ?
推荐答案
每个事件只有一个keyCode
.您必须跟踪向上和向下的键:
There's only one keyCode
per event. You have to track the keys going down, and up:
// if you keep both up and down keys down, you'll get a message
let downKeys = {}; // the set of keys currently down
document.addEventListener('keydown', event => {
downKeys[event.keyCode] = true;
if (downKeys[38] && downKeys[40]) {
console.log("both down!");
}
});
document.addEventListener('keyup', event => {
downKeys[event.keyCode] = false;
});
(您必须进入整页才能测试此代码段)
(you have to go full page to test this snippet)
这篇关于同时检测到两个键盘按键被按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文