Bind Multiple Keys to Keypress Event

不问归期 提交于 2019-11-27 05:42:03

问题


I am currently using this Javascript kepypress 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;
    }
});

回答1:


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).

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

Example:

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



回答2:


Why not use if rather than switch?

$(document).keydown(function(e) {
    if ((e.keyCode === 37) || (e.keyCode === 39)) {
        e.preventDefault();
        alert("Arrow Key");
    }
});



回答3:


You can use the case fallthrough:

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

Note that I'm using e.which instead of e.keyCode to make it work in all browsers (jQuery automatically assigns the property which actually contains the key code to e.which).



来源:https://stackoverflow.com/questions/4173460/bind-multiple-keys-to-keypress-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!