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

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

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


当前回答

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;

其他回答

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

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

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

我已经能够用jQuery捕获它们:

$(document).keypress(function (eventObject) {
    alert(eventObject.keyCode);
});

示例:http://jsfiddle.net/AjKjU/

与键和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>

对于不可打印的键,如方向键,使用向下键,而不是按下键:

function checkKey(e) {
    e = e || window.event;
    alert(e.keyCode);
}

document.onkeydown = checkKey;

我找到的最好的JavaScript键事件参考资料(例如,打败quirksmode)在这里:http://unixpapa.com/js/key.html

我是这样做的:

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