Detecting arrow key presses in JavaScript

2018-12-31 21:05发布

How do I detect when one of the arrow keys are pressed? I used this to find out:

function checkKey(e) {
    var event = window.event ? window.event : e;
    console.log(event.keyCode)
}

Though it worked for every other key, it didn't for arrow keys (maybe because the browser is supposed to scroll on these keys by default).

16条回答
ら面具成の殇う
2楼-- · 2018-12-31 21:59

Possibly the tersest formulation:

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            alert('left');
            break;
        case 38:
            alert('up');
            break;
        case 39:
            alert('right');
            break;
        case 40:
            alert('down');
            break;
    }
};

Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/

This should work cross-browser. Leave a comment if there is a browser where it does not work.

There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html. Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.

查看更多
浪荡孟婆
3楼-- · 2018-12-31 22:02

Re answers that you need keydown not keypress.

Assuming you want to move something continuously while the key is pressed, I find that keydown works for all browsers except Opera. For Opera, keydown only triggers on 1st press. To accommodate Opera use:

document.onkeydown = checkKey;
document.onkeypress = checkKey;
function checkKey(e)
{ etc etc
查看更多
浮光初槿花落
4楼-- · 2018-12-31 22:06
function checkArrowKeys(e){
    var arrs= ['left', 'up', 'right', 'down'], 
    key= window.event? event.keyCode: e.keyCode;
    if(key && key>36 && key<41) alert(arrs[key-37]);
}
document.onkeydown= checkArrowKeys;
查看更多
孤独总比滥情好
5楼-- · 2018-12-31 22:06

Here's how I did it:

var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
    keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
    delete keystate[e.keyCode];
});

if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}
查看更多
登录 后发表回答