简体   繁体   中英

Check if key combination is not pressed

I need to check if the key combination ctrl + alt is not pressed.

To check if the key combination is pressed you can use a simple if statement:

if (e.ctrlKey && e.altKey) {
   console.log("ctrl and alt pressed")
}

But how can I check of this key combination is not pressed? I´ve tried to invert the if statment but this did not work:

document.addEventListener("keydown", keyDownFunc, false);

function keyDownFunc(e) {
    if (!(e.ctrlKey && e.altKey)) {
    console.log("not pressed");
    }
}

https://jsfiddle.net/xela84/39cq5oja/1/

I need that to switch a radiobutton with the arrow keys only if the Alt Gr key is not pressed:

this.addEventListener('keydown', e => {
    // if e.target is vaadin-radio-group then assign to checkedRadioButton currently checked radio button
    var checkedRadioButton = (e.target == this) ? this._checkedButton : e.target;

    // Detect if Alt Gr is not pressed
    if (!e.ctrlKey && !e.altKey) {

        // LEFT, UP - select previous radio button
        if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
            e.preventDefault();
            this._selectPreviousButton(checkedRadioButton);
        }

        // RIGHT, DOWN - select next radio button
        if (e.key === "ArrowRight" || e.key === "ArrowDown") {
            e.preventDefault();
            this._selectNextButton(checkedRadioButton);
        }
    }
});

At the first key you pressed, the code will act like CTRL and Alt are not pressed even if you try to press them at the same time.

Still, you can check it with a simple else statement.

if(e.altKey && e.ctrlKey) {
    // some code here
} else {
    // here is the part of NOT pressing ctrl and alt together
}

Demo from here: JSFiddle

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