如果用户在javascript中按下两个键,该怎么做

Mod*_*ner 2 javascript keyboard jquery shortcut

所以我写了这个脚本,以便你可以在你的网站上有键盘快捷键,我想知道如何做多个键(即不只是做"左箭头"键,它将是"ctrl +左箭头".这里是我目前的语法:

var arrow = {
    left: 37,
    up: 38,
    right: 39,
    down: 40
};

function DoSomething() {}

$(document).ready(function() { // requires jQuery
    $("body").keydown(function(event) {
        if(event.keyCode == arrow.left) {
            DoSomething();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我想做的是这样的事情:

var arrow = {
    left: 37,
    up: 38,
    right: 39,
    down: 40
},

ctrl = 17;

function DoSomething() {}

$(document).ready(function() { // requires jQuery
    $("body").keydown(function(event) {
        if(event.keyCode == ctrl && arrow.left) {
            DoSomething();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*son 5

jQuery中提供的事件对象告诉您是否ctrl按下了键.

$(document).on("keydown", function (event) {
    if (event.ctrlKey && event.which === arrow.left) {
        console.log("You pressed left, and control.");
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/zcMXR/

  • @JonathanSampson你的意思是`&& event.keyCode == arrow.left`?否则,它只测试arrow.left的有效性,作为非零数字,它将始终评估为true. (2认同)