Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
322 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...