JavaScript 检查键盘状态
我正在制作一个简单的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以同时使用 onkeydown 和 onkeyup:
使用此代码,您可以将每个按下的按键代码存储在
pressed
变量中,然后在松开按键时将其删除。因此,当您需要知道按下了哪些键时,可以使用 for(..in..) 循环遍历按下的对象。You can use onkeydown and onkeyup together:
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.