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

时间:2012-11-20 16:10:53

标签: javascript jquery keyboard 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();
        }
    }
}

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

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

2 个答案:

答案 0 :(得分:5)

jQuery中提供的事件对象会告诉您是否正在按下ctrl键。

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

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

答案 1 :(得分:1)

jQuery已经做到了。除了跟踪按下了哪个键之外,您还可以获得有关键是否与altctrlshift组合使用的信息,其属性如下所示:

$(document).keydown(function(e) {
      console.log('key code is: ' + e.which + ' ' + (e.ctrlKey ? 'Ctrl' : '') + ' ' +
            (e.shiftKey ? 'Shift' : '') + ' ' + (e.altKey ? 'Alt' : ''));
});

因此,要检查键组合是否为Ctrl + Up,您的条件将如下所示:

if( e.which == 38 && e.ctrlKey ){
    console.log('You pressed Ctrl+Up');
    ...
}
相关问题