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

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

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


当前回答

方向键在keyup时触发

$(document).on("keyup", "body", function(e) {
 if (e.keyCode == 38) {
    // up arrow
    console.log("up arrow")
  }
  if (e.keyCode == 40) {
      // down arrow
      console.log("down arrow")
  }
  if (e.keyCode == 37) {
    // left arrow
    console.log("lefy arrow")
  }
  if (e.keyCode == 39) {
    // right arrow
    console.log("right arrow")
  }
})

Onkeydown允许ctrl, alt,屎

Onkeyup允许标签,向上箭头,向下箭头,向左箭头,向下箭头

其他回答

这是短的。

函数IsArrows (e) { return (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.
}

方向键在keyup时触发

$(document).on("keyup", "body", function(e) {
 if (e.keyCode == 38) {
    // up arrow
    console.log("up arrow")
  }
  if (e.keyCode == 40) {
      // down arrow
      console.log("down arrow")
  }
  if (e.keyCode == 37) {
    // left arrow
    console.log("lefy arrow")
  }
  if (e.keyCode == 39) {
    // right arrow
    console.log("right arrow")
  }
})

Onkeydown允许ctrl, alt,屎

Onkeyup允许标签,向上箭头,向下箭头,向左箭头,向下箭头

如果你使用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');
    }
 });

方向键只能由onkeydown触发,而不是onkeypress。

键码是:

左= 37 Up = 38 右= 39 下降= 40