简体   繁体   English

在javascript中,您如何检测用户是否按住了键?

[英]In javascript how do you detect if the user held a key or not?

I am trying to make a game which has the feature that if you hold the shift key, the player will speed up. 我正在尝试制作一款具有以下功能的游戏:如果您按住Shift键,则玩家将加快速度。 I tried to use keyEvent but it can't detect the key is held or pressed. 我尝试使用keyEvent,但无法检测到该键被按住。 and when I release the shift key, the player remains in speed up mode and won't change the speed back to normal. 当我松开Shift键时,播放器将保持加速模式,并且不会将速度恢复为正常。 is there any possible way to achieve this? 有什么可能的方法来实现这一目标?

You should listen for two events: keydown and keyup . 您应该听两个事件: keydownkeyup In every event type you should check for key (the keycode of "shift" is 16), and on keydown you should start an action, and on keyup stop it (if event.keyCode === 16 ). 在每一个事件类型,你应该检查键(“移动”的键码是16),并在keydown你应该开始行动,并在keyup停止它(如果event.keyCode === 16 )。 Here is a simple example with text color, it becomes red while "shift" is pressed (don't forget to click on opened window of the snippet, it will not work without it because without focusing on this window all events will be "out of scope" for the snippet): 这是一个带有文本颜色的简单示例,按下“ shift”按钮时该颜色变为红色(不要忘了单击该片段的打开的窗口,如果没有它,它将不起作用,因为如果不关注此窗口,所有事件都将“退出”摘录”):

 var onkeydown = (function (e) { if (e.keyCode === 16) { document.getElementById("target").style.color = "red"; } }); var onkeyup = (function (e) { if (e.keyCode === 16) { document.getElementById("target").style.color = "black"; } }); 
 <h1 id="target">Red when holds "shift"</h1> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM