检查是否没有按下组合键

时间:2019-10-21 12:50:15

标签: javascript

我需要检查是否没有按下组合键ctrl + alt

要检查是否按下了组合键,可以使用简单的if语句:

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

但是如何检查此键组合是否未按下? 我试图将if语句反转,但这没用:

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

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

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

只有在未按下Alt Gr键的情况下,我才需要使用箭头键切换单选按钮:

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);
        }
    }
});

0 个答案:

没有答案