在 JavaScript 中检测箭头键按下

发布于 2024-10-30 22:38:19 字数 214 浏览 1 评论 0原文

如何检测何时按下方向键之一?我用这个来找出:

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

樱&纷飞 2024-11-06 22:38:19

箭头键仅由 onkeydown 触发,而不是由 onkeypress 触发。

键码为:

  • 左 = 37
  • 上 = 38
  • 右 = 39
  • 下 = 40

Arrow keys are only triggered by onkeydown, not onkeypress.

The keycodes are:

  • left = 37
  • up = 38
  • right = 39
  • down = 40
浅浅淡淡 2024-11-06 22:38:19

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

更新且更清晰:使用 event.key。不再有任意数字代码!如果您正在进行编译或知道您的用户都使用现代浏览器,请使用它!

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

详细处理:

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

现代开关处理:

const callback = {
    "ArrowLeft"  : leftHandler,
    "ArrowRight" : rightHandler,
    "ArrowUp"    : upHandler,
    "ArrowDown"  : downHandler,
}[event.key]
callback?.()

注意:旧属性(.keyCode.which)已弃用。

"w", "a", "s", "d" 作为方向,使用 event.code

为了支持使用非 qwerty/英文键盘布局的用户,您应该使用event.code。即使最终的字符发生变化,这也将保留物理键位置。

event.key 在 Dvorak 上将是 ,,在 Azerty 上将是 z,从而使您的游戏无法玩。

const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD

最理想的是,您还允许按键重新映射,这对玩家有利,无论他们的情况如何。

PS event.code 与箭头相同

key Mozilla 文档

代码 Mozilla 文档

支持的浏览器

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!

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

Modern Switch Handling:

const callback = {
    "ArrowLeft"  : leftHandler,
    "ArrowRight" : rightHandler,
    "ArrowUp"    : upHandler,
    "ArrowDown"  : downHandler,
}[event.key]
callback?.()

NOTE: The old properties (.keyCode and .which) are Deprecated.

"w", "a", "s", "d" for direction, use event.code

To support users who are using non-qwerty/English keyboard layouts, you should instead use event.code. This will preserve physical key location, even if resulting character changes.

event.key would be , on Dvorak and z on Azerty, making your game unplayable.

const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD

Optimally, you also allow key remapping, which benefits the player regardless of their situation.

P.S. event.code is the same for arrows

key Mozilla Docs

code Mozilla Docs

Supported Browsers

茶花眉 2024-11-06 22:38:19

按键上下通话功能。每个键都有不同的代码。

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
    }

}

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
    }

}
ま昔日黯然 2024-11-06 22:38:19

可能是最简洁的表述:

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

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

这应该可以跨浏览器工作。如果有浏览器不工作的地方请发表评论。

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

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/

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.

德意的啸 2024-11-06 22:38:19

对于不可打印的按键(例如箭头键),请使用 keydown,而不是 keypress

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

document.onkeydown = checkKey;

我发现的最佳 JavaScript 按键事件参考(例如,击败怪异模式)是这里:http://unixpapa.com/js/key.html

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

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

明月夜 2024-11-06 22:38:19

keyCode 现已弃用以来的现代答案< /strong> 支持 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
    }
};

Modern answer since keyCode is now deprecated in favor of 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
    }
};
风流物 2024-11-06 22:38:19

我相信最新的方法是:

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

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

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.

过度放纵 2024-11-06 22:38:19
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;
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;
小鸟爱天空丶 2024-11-06 22:38:19

这是一个示例实现:

var targetElement = $0 || 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);
  }
});

Here's an example implementation:

var targetElement = $0 || 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);
  }
});
Spring初心 2024-11-06 22:38:19

我是这样做的:

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

Here's how I did it:

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.
}
·深蓝 2024-11-06 22:38:19

箭头键在 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、shit

onkeyup 允许 tab、向上箭头、向下箭头、向左箭头、向下箭头

Arrow Keys are triggered on 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 allows ctrl, alt, shits

onkeyup allows tab, up arrows, down arrows, left arrows, down arrows

陌若浮生 2024-11-06 22:38:19

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

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

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

I've been able to trap them with jQuery:

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

An example: http://jsfiddle.net/AjKjU/

猫性小仙女 2024-11-06 22:38:19

这是 chrome 和 firefox 的工作代码

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script type="text/javascript">

    function leftArrowPressed() {
      alert("leftArrowPressed" );
      window.location = prevUrl  
    }

    function rightArrowPressed() {
      alert("rightArrowPressed" );
      window.location = nextUrl  
    }
    function topArrowPressed() {
      alert("topArrowPressed" );
      window.location = prevUrl  
    }

    function downArrowPressed() {
      alert("downArrowPressed" );
      window.location = nextUrl  
    }

        document.onkeydown = function(evt) {
                        var nextPage = $("#next_page_link")
                        var prevPage = $("#previous_page_link")
                        nextUrl = nextPage.attr("href")
                        prevUrl = prevPage.attr("href")
        evt = evt || window.event;
        switch (evt.keyCode) {
                case 37:
                leftArrowPressed(nextUrl);
                break;

                case 38:
                topArrowPressed(nextUrl);
                break;

                 case 39:
                rightArrowPressed(prevUrl);
                break;

                case 40:
                downArrowPressed(prevUrl);
                break;

        }
    };


</script>
</head>
<body>
<p>
<a id="previous_page_link" href="http://www.latest-tutorial.com">Latest Tutorials</a> 
<a id="next_page_link" href="http://www.zeeshanakhter.com">Zeeshan Akhter</a>
 </p>
</body>
</html>

That is the working code for chrome and firefox

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script type="text/javascript">

    function leftArrowPressed() {
      alert("leftArrowPressed" );
      window.location = prevUrl  
    }

    function rightArrowPressed() {
      alert("rightArrowPressed" );
      window.location = nextUrl  
    }
    function topArrowPressed() {
      alert("topArrowPressed" );
      window.location = prevUrl  
    }

    function downArrowPressed() {
      alert("downArrowPressed" );
      window.location = nextUrl  
    }

        document.onkeydown = function(evt) {
                        var nextPage = $("#next_page_link")
                        var prevPage = $("#previous_page_link")
                        nextUrl = nextPage.attr("href")
                        prevUrl = prevPage.attr("href")
        evt = evt || window.event;
        switch (evt.keyCode) {
                case 37:
                leftArrowPressed(nextUrl);
                break;

                case 38:
                topArrowPressed(nextUrl);
                break;

                 case 39:
                rightArrowPressed(prevUrl);
                break;

                case 40:
                downArrowPressed(prevUrl);
                break;

        }
    };


</script>
</head>
<body>
<p>
<a id="previous_page_link" href="http://www.latest-tutorial.com">Latest Tutorials</a> 
<a id="next_page_link" href="http://www.zeeshanakhter.com">Zeeshan Akhter</a>
 </p>
</body>
</html>
梦幻的味道 2024-11-06 22:38:19

我也在寻找这个答案,直到我看到这篇文章。

我找到了另一种解决方案来了解不同键的键码,以解决我的问题。我只是想分享我的解决方案。

只需使用 keyup/keydown 事件在控制台/警报中写入相同的值,使用 event.keyCode 。就像

console.log(event.keyCode) 

// or

alert(event.keyCode)

--rupam

I was also looking for this answer until I came across this post.

I've found another solution to know the keycode of the different keys, courtesy to my problem. I just wanted to share my solution.

Just use keyup/keydown event to write the value in the console/alert the same using event.keyCode. like-

console.log(event.keyCode) 

// or

alert(event.keyCode)

- rupam

安静 2024-11-06 22:38:19

那个更短。

函数 IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}

That's shorter.

function IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}

初雪 2024-11-06 22:38:19

这个图书馆太棒了!
https://craig.is/killing/mice

Mousetrap.bind('up up down down left right left right b a enter', function() {
    highlight([21, 22, 23]);
});

您需要快速按下序列才能突出显示不过该页面中的代码。

This library rocks!
https://craig.is/killing/mice

Mousetrap.bind('up up down down left right left right b a enter', function() {
    highlight([21, 22, 23]);
});

You need to press the sequence a bit fast to highlight the code in that page though.

深海不蓝 2024-11-06 22:38:19

使用 key 和 ES6。

这为您提供了每个箭头键的单独功能,而无需使用开关,并且当 NumLock 打开时,还可以使用数字键盘中的 2、4、6、8 键。

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>

With key and ES6.

This gives you a separate function for each arrow key without using switch and also works with the 2,4,6,8 keys in the numpad when NumLock is on.

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>

酒废 2024-11-06 22:38:19

如果您在 2023 年仍在考虑桌面开发:

KeyboardEvent: keyCode property 已被弃用

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

使用 key 属性
https://developer.mozilla .org/en-US/docs/Web/API/KeyboardEvent/key

// run snippet and click a key to see which key you clicked:

document.addEventListener('keydown', (event) => { 
 alert(`You clicked ${event.key}`);
});

In the off chance you're still developing with desktops in mind in 2023:

KeyboardEvent: keyCode property has been deprecated

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Use the key property
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

// run snippet and click a key to see which key you clicked:

document.addEventListener('keydown', (event) => { 
 alert(`You clicked ${event.key}`);
});

微凉 2024-11-06 22:38:19

重新回答您需要 keydown 而不是 keypress

假设您想在按下按键时连续移动某些东西,我发现 keydown 适用于除 Opera 之外的所有浏览器。对于 Opera,keydown 仅在第一次按下时触发。为了适应 Opera 使用:

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

Re answers that you need keydown not keypress.

Assuming you want to move something continuously while the key is pressed, I find that keydown works for all browsers except Opera. For Opera, keydown only triggers on 1st press. To accommodate Opera use:

document.onkeydown = checkKey;
document.onkeypress = checkKey;
function checkKey(e)
{ etc etc
别把无礼当个性 2024-11-06 22:38:19

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

If you use jquery then you can also do like this,

 $(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');
    }
 });
阳光下慵懒的猫 2024-11-06 22:38:19

控制键代码 %=37&=38...并且仅箭头键 left=37 up=38

function IsArrows (e) {
   return ( !evt.shiftKey && (e.keyCode >= 37 && e.keyCode <= 40)); 
}

control the Key codes %=37 and &=38... and only arrow keys left=37 up=38

function IsArrows (e) {
   return ( !evt.shiftKey && (e.keyCode >= 37 && e.keyCode <= 40)); 
}
诠释孤独 2024-11-06 22:38:19

如果你想检测箭头按键但不需要在 Javascript 中指定

function checkKey(e) {
   if (e.keyCode !== 38 || e.keyCode !== 40 || e.keyCode !== 37 || e.keyCode !== 39){
    // do something
   };
}

If you want to detect arrow keypresses but not need specific in Javascript

function checkKey(e) {
   if (e.keyCode !== 38 || e.keyCode !== 40 || e.keyCode !== 37 || e.keyCode !== 39){
    // do something
   };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文