简体   繁体   中英

How to trigger an event when three keyboards are pressed at the same time in Javascript

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

Change the order of the conditions, as the first condition is always true if the second is true , causing the code for the second condition to never execute.

document.onkeydown = function(e) {
    if (e.ctrlKey && e.shiftKey && e.key === 'Z') {
        undo()
    } else if (e.ctrlKey && e.key === 'Z') {
        redo();
    }
}

I nice way to keep track of pressed keys is with an object:

const keys = {}

function onKeyDown(e) {
    keys[e.key.toLowerCase()] = true
    doSomething()
}

function onKeyUp(e) {
    keys[e.key.toLowerCase()] = false
}

window.addEventListener('keydown', onKeyDown)
window.addEventListener('keyup', onKeyUp)

function doSomething() {
    console.log(keys)
    if (keys.control && keys.shift && keys.z) {
        console.log("redo!")
    } else if (keys.control && keys.z) {
        console.log("undo!")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM