javascript 按住箭头键时的Javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5254802/
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
Javascript when holding down arrow keys?
提问by Trevor Rudolph
I have this script to trigger some javascript. But the script does not support holding down the arrow keys. How can I make this work when I hold the arrow keys.
我有这个脚本来触发一些 javascript。但该脚本不支持按住箭头键。当我按住箭头键时,我怎样才能做到这一点。
document.onkeyup = KeyCheck;
function KeyCheck()
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 37:
right('img'); document.getElementById('img').src = 'guyl.png';
break;
case 38:
up('img');
break
case 39:
left('img'); document.getElementById('img').src = 'guyr.png';
break;
case 40:
down('img');
break;
}
}
回答by Raptor
should be:
应该:
document.onkeydown = KeyCheck;
onkeypress : invokes JavaScript code when a key is pressed
onkeypress : 当一个键被按下时调用 JavaScript 代码
onkeydown : invokes JavaScript code when a key is held down (but not yet released)
onkeydown :当一个键被按下(但尚未释放)时调用 JavaScript 代码
onkeyup : invokes JavaScript code when a key is has been released after being pressed.
onkeyup :当按键被按下后释放时调用 JavaScript 代码。
回答by SLaks
You just need to handle the onkeydownevent.
你只需要处理onkeydown事件。
回答by stac
correct your function to accept the event arg
function KeyCheck(event) {
var KeyID = event.keyCode;
...
}
if you want to use combination of keys, then use onkeypress event instead, push the keys into array and see if you have desired combination to follow.
更正您的函数以接受事件 arg
功能键检查(事件){
var KeyID = event.keyCode;
...
}
如果您想使用按键组合,请改用 onkeypress 事件,将按键推入数组并查看您是否需要遵循所需的组合。

