将多个键绑定到 Keypress 事件

Bind Multiple Keys to Keypress Event(将多个键绑定到 Keypress 事件)

本文介绍了将多个键绑定到 Keypress 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用这个 Javascript 按键代码在按键时触发事件:

I am currently using this Javascript keypress code to fire events upon keypress:

$(document).keydown(function(e) {
    switch(e.keyCode) {

    case 39:
        e.preventDefault();
        alert("Arrow Key");
        break;

    case 37:
        e.preventDefault();
        alert("Arrow Key");
    }
});

但我想知道的是,我是否可以绑定两个键的组合而不是绑定一个键.我可以做类似的事情吗:

but what I am wondering is if I can instead of binding one key bind a combination of two keys. Could I possibly do something like:

$(document).keydown(function(e) {
    switch(e.keyCode) { 
        case 39 && 37:
            e.preventDefault();
            alert("Arrow Key");
        break;
    }
});

推荐答案

如果你想一次检查多个键,你应该只使用一个常规键和一个或多个修饰键(alt/shift/ctrl),因为你不能确保在用户的键盘上实际上可以同时按下两个常规键(实际上,它们总是可以按下,但由于键盘的接线方式,PC 可能无法理解).

If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).

您可以使用 e.altKey、e.ctrlKey、e.shiftKey 字段来检查是否按下了匹配的修饰键.

You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.

例子:

$(document).keydown(function(e) {
    if(e.which == 98 && e.ctrlKey) {
        // ctrl+b pressed
    }
});

这篇关于将多个键绑定到 Keypress 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将多个键绑定到 Keypress 事件

基础教程推荐