如何检测 JavaScript 中的箭头按键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30045144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:33:50  来源:igfitidea点击:

How to detect arrow key-presses in JavaScript?

javascriptjquerykeypresskeyboard-eventsarrow-keys

提问by Ashish Ahuja

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?

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

回答by NickOS

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

回答by Rav's Patel

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

回答by Sunil B N

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

}

}