Detecting two keyboard keys being down at the same time

佐手、 提交于 2020-01-13 12:06:25

问题


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 ?


回答1:


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)




回答2:


Here I use 2 flags to check if you are holding the keys.

If both flags are true then it means that you are holding both keys. So, you can perform anything inside the condition.

let holdKeyUp = false;
let holdKeyRight = false;

document.addEventListener('keydown', event => {

    if (event.keyCode === 38) {
        holdKeyUp = true;
    }

    if (event.keyCode === 39) {
        holdKeyRight = true;
    }
    
    if (holdKeyUp && holdKeyRight) {
        console.log("Both keys are pressed.");
    }

})

document.addEventListener('keyup', event => {

    if (event.keyCode === 38) {
        holdKeyUp = false;
    }

    if (event.keyCode === 39) {
        holdKeyRight = false;
    }

})


来源:https://stackoverflow.com/questions/53882013/detecting-two-keyboard-keys-being-down-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!