检测 JavaScript 中的箭头键按下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5597060/
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-08-23 17:58:46  来源:igfitidea点击:

Detecting arrow key presses in JavaScript

javascriptkeypresskeyboard-events

提问by mihsathe

How do I detect when one of the arrow keys are pressed? I used this to find out:

如何检测何时按下了其中一个箭头键?我用这个来找出:

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

Though it worked for every other key, it didn't for arrow keys (maybe because the browser is supposed to scroll on these keys by default).

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

回答by Mark Kahn

Arrow keys are only triggered by onkeydown, not onkeypress.

箭头键只能由 触发onkeydown,而不是由 触发onkeypress

The keycodes are:

密钥代码是:

  • left = 37
  • up = 38
  • right = 39
  • down = 40
  • 左 = 37
  • 向上 = 38
  • 右 = 39
  • 向下 = 40

回答by ketan

On key up and down call function. There are different codes for each key.

上键上下调用功能。每个键都有不同的代码。

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
        // up arrow
    }
    else if (e.keyCode == '40') {
        // down arrow
    }
    else if (e.keyCode == '37') {
       // left arrow
    }
    else if (e.keyCode == '39') {
       // right arrow
    }

}

回答by Gibolt

event.key === "ArrowRight"...

event.key === "ArrowRight"...

More recent and much cleaner: use event.key. No more arbitrary number codes! If you are transpiling or know your users are all on modern browsers, use this!

更新更干净:使用event.key. 没有更多的任意数字代码!如果您正在转译或知道您的用户都在使用现代浏览器,请使用它!

node.addEventListener('keydown', function(event) {
    const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
});

Verbose Handling:

详细处理:

switch (event.key) {
    case "ArrowLeft":
        // Left pressed
        break;
    case "ArrowRight":
        // Right pressed
        break;
    case "ArrowUp":
        // Up pressed
        break;
    case "ArrowDown":
        // Down pressed
        break;
}

You can easily extend this to check for "w", "a", "s", "d", or any other key

您可以轻松扩展它以检查"w", "a", "s", "d",或任何其他键

Mozilla Docs

Mozilla 文档

Supported Browsers

支持的浏览器

P.S. event.codeis the same for arrows

PSevent.code箭头相同

回答by 1''

Possibly the tersest formulation:

可能是最简洁的公式:

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

Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/

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

This should work cross-browser. Leave a comment if there is a browser where it does not work.

这应该跨浏览器工作。如果浏览器不起作用,请发表评论。

There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html. Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.

还有其他方法可以获取关键代码(e.which、e.charCode 和 window.event 而不是 e),但它们不是必需的。您可以在http://www.asquare.net/javascript/tests/KeyCode.html 上尝试其中的大部分。请注意 event.keycode 不适用于 Firefox 中的 onkeypress,但它适用于 onkeydown。

回答by Tim Down

Use keydown, not keypressfor non-printable keys such as arrow keys:

使用keydown, 不适keypress用于不可打印的键,例如箭头键:

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

document.onkeydown = checkKey;

The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html

我找到的最好的 JavaScript 关键事件参考(例如,在 quirksmode 中击败裤子)在这里:http: //unixpapa.com/js/key.html

回答by Joshua Fan

Modern answer since keyCodeis now deprecatedin favor of key:

现代答案,因为现在不推荐使用keyCode以支持key

document.onkeydown = function (e) {
    switch (e.key) {
        case 'ArrowUp':
            // up arrow
            break;
        case 'ArrowDown':
            // down arrow
            break;
        case 'ArrowLeft':
            // left arrow
            break;
        case 'ArrowRight':
            // right arrow
    }
};

回答by lrhorer

I believe the most recent method would be:

我相信最近的方法是:

document.addEventListener("keydown", function(event) {
  event.preventDefault();
  const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
  switch (key) { // change to event.key to key to use the above variable
    case "ArrowLeft":
      // Left pressed
      <do something>
      break;
    case "ArrowRight":
      // Right pressed
      <do something>
      break;
    case "ArrowUp":
      // Up pressed
      <do something>
      break;
    case "ArrowDown":
      // Down pressed
      <do something>
      break;
  }
});

This assumes the developer wants the code to be active anywhere on the page and the client should ignore any other key presses. Eliminate the event.preventDefault(); line if keypresses, including those caught by this handler should still be active.

这假设开发人员希望代码在页面上的任何位置都处于活动状态,并且客户端应该忽略任何其他按键。消除 event.preventDefault(); 行 if 按键,包括由该处理程序捕获的按键仍应处于活动状态。

回答by kennebec

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;

回答by RobPW

Here's an example implementation:

这是一个示例实现:

var targetElement = 
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.
}
|| document.body; function getArrowKeyDirection (keyCode) { return { 37: 'left', 39: 'right', 38: 'up', 40: 'down' }[keyCode]; } function isArrowKey (keyCode) { return !!getArrowKeyDirection(keyCode); } targetElement.addEventListener('keydown', function (event) { var direction, keyCode = event.keyCode; if (isArrowKey(keyCode)) { direction = getArrowKeyDirection(keyCode); console.log(direction); } });

回答by OneStig

Here's how I did it:

这是我如何做到的:

##代码##