我如何检测当一个方向键被按下?我用这个找到了答案:

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

虽然它适用于所有其他键,但它不适用于方向键(可能是因为浏览器默认情况下应该在这些键上滚动)。


当前回答

与键和ES6。

这为您提供了一个单独的功能,每个方向键,而不使用开关,也适用于2,4,6,8键在NumLock是在numpad。

const element = document.querySelector("textarea"), ArrowRight = k => { console.log(k); }, ArrowLeft = k => { console.log(k); }, ArrowUp = k => { console.log(k); }, ArrowDown = k => { console.log(k); }, handler = { ArrowRight, ArrowLeft, ArrowUp, ArrowDown }; element.addEventListener("keydown", e => { const k = e.key; if (handler.hasOwnProperty(k)) { handler[k](k); } }); <p>Click the textarea then try the arrows</p> <textarea></textarea>

其他回答

控制键码%=37和&=38…只有箭头键左=37向上=38

function IsArrows (e) {
   return ( !evt.shiftKey && (e.keyCode >= 37 && e.keyCode <= 40)); 
}

我是这样做的:

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

如果你使用jquery,你也可以这样做,

 $(document).on("keydown", '.class_name', function (event) {
    if (event.keyCode == 37) {
        console.log('left arrow pressed');
    }
    if (event.keyCode == 38) {
        console.log('up arrow pressed');
    }
    if (event.keyCode == 39) {
        console.log('right arrow pressed');
    }
    if (event.keyCode == 40) {
        console.log('down arrow pressed');
    }
 });

可能是最简洁的表述:

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

演示(感谢用户Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/

这应该可以跨浏览器工作。如果有浏览器无法使用,请留下评论。

还有其他方法来获取键代码(e.c iwhich, e.c arcode和window。事件而不是e),但它们不应该是必要的。你可以在http://www.asquare.net/javascript/tests/KeyCode.html上尝试其中的大部分。 注意这个事件。keycode在Firefox中不与onkeypress一起工作,但它与onkeydown一起工作。

你需要按下键,而不是按下键。

假设你想在按下键的同时连续移动一些东西,我发现除了Opera以外,所有浏览器都可以按下键。对于Opera,按键只在第一次按下时触发。为了适应Opera的使用:

document.onkeydown = checkKey;
document.onkeypress = checkKey;
function checkKey(e)
{ etc etc