如何在JavaScript中检测箭头按键? [重复]

时间:2022-11-06 17:23:52

This question already has an answer here:

这个问题在这里已有答案:

I am making a car racing game in JavaScript. The car is controlled by the arrow keys. I have made a lot of games in JavaScript before and it worked.
The code I had used is:

我正在使用JavaScript制作赛车游戏。汽车由箭头键控制。我之前在JavaScript中制作了很多游戏并且它有效。我使用的代码是:

function detectKey(e) {
    var event = window.event ? window.event : e;
    if (true) {
        alert(event.keyCode)
    }
}

Now I am using this code the first time for arrow keys. Whenever I press the arrow keys the the page is moving up and down. I am not understanding the problem. Can somebody help?

现在我第一次使用此代码用于箭头键。每当我按下箭头键时,页面就会上下移动。我不明白这个问题。有人可以帮忙吗?

3 个解决方案

#1


Heres a list of all the keycodes http://mikemurko.com/general/jquery-keycode-cheatsheet/
- Enter: 13 - Up: 38 - Down: 40 - Right: 39 - Left: 37

下面是所有密码的列表http://mikemurko.com/general/jquery-keycode-cheatsheet/ - 输入:13 - 上:38 - 下:40 - 右:39 - 左:37

    $(document).keyup(function(e) {
        if (e.which === 38) {
          //up was pressed
        }
    });

#2


Use keyCode like below :

使用keyCode,如下所示:

$(document).on('keypress','your-element',function(e){
    if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)
    console.log("Arrow key pressed");
})

#3


in pure JavaScript

在纯JavaScript中

document.onkeydown = function myFunction() {
switch (event.keyCode) {
case 38:
    console.log("Up key is pressed");
    break;
case 40:
    console.log("Down key is pressed");
    break;
case 37:
    console.log("Right key is pressed");
    break;
case 39:
    console.log("left key is pressed");
    break;
}

}

#1


Heres a list of all the keycodes http://mikemurko.com/general/jquery-keycode-cheatsheet/
- Enter: 13 - Up: 38 - Down: 40 - Right: 39 - Left: 37

下面是所有密码的列表http://mikemurko.com/general/jquery-keycode-cheatsheet/ - 输入:13 - 上:38 - 下:40 - 右:39 - 左:37

    $(document).keyup(function(e) {
        if (e.which === 38) {
          //up was pressed
        }
    });

#2


Use keyCode like below :

使用keyCode,如下所示:

$(document).on('keypress','your-element',function(e){
    if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)
    console.log("Arrow key pressed");
})

#3


in pure JavaScript

在纯JavaScript中

document.onkeydown = function myFunction() {
switch (event.keyCode) {
case 38:
    console.log("Up key is pressed");
    break;
case 40:
    console.log("Down key is pressed");
    break;
case 37:
    console.log("Right key is pressed");
    break;
case 39:
    console.log("left key is pressed");
    break;
}

}