JavaScript 检查键盘状态

发布于 2024-10-07 18:44:50 字数 193 浏览 0 评论 0原文

我正在制作一个简单的 Javascript 游戏,需要能够检查是否按下了某些键。我尝试绑定到 onkeydown 事件,但我遇到的问题是双重的:首先,它不允许我检查是否同时按下了多个键。其次,它会在按住该键后暂停,然后开始发送垃圾邮件事件。

在我的代码中,我可以有一个事件或一个函数来每毫秒检查一次以查看是否按下了按键。既然这是一个游戏,我真的没有任何问题。

I am working on making a simple Javascript game and need to be able to check if certain keys are being pressed. I have tried binding to the onkeydown event, but the problem that I am having is twofold: first, it won't let me check to see if more than one key is being pressed at any time. And second, it pauses after holding the key down before it starts spamming the event.

In my code, I could either have an event, or a function that checks every millisecond to see if the key is being pressed. Seeing as this is a game, I would really have no problem with either.

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

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

发布评论

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

评论(1

猛虎独行 2024-10-14 18:44:50

您可以同时使用 onkeydown 和 onkeyup:

var pressed={};
element.onkeydown=function(e){
     e = e || window.event;
     pressed[e.keyCode] = true;
}

element.onkeyup=function(e){
     e = e || window.event;
     delete pressed[e.keyCode];
}

使用此代码,您可以将每个按下的按键代码存储在 pressed 变量中,然后在松开按键时将其删除。因此,当您需要知道按下了哪些键时,可以使用 for(..in..) 循环遍历按下的对象。

You can use onkeydown and onkeyup together:

var pressed={};
element.onkeydown=function(e){
     e = e || window.event;
     pressed[e.keyCode] = true;
}

element.onkeyup=function(e){
     e = e || window.event;
     delete pressed[e.keyCode];
}

with this code you store every pressed key code in the pressed variable and then you delete it when the key is released. So when you need to know which keys are pressed you can loop with a for(..in..) through the pressed object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文