简体   繁体   中英

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. I tried to use keyEvent but it can't detect the key is held or pressed. and when I release the shift key, the player remains in speed up mode and won't change the speed back to normal. is there any possible way to achieve this?

You should listen for two events: keydown and keyup . 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 ). 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):

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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