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

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

javascript - Bind Multiple Keys to Keypress Event

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...