简体   繁体   中英

How to check if a key (on the keyboard) is being held down?

Basically title. I need a function which works kind of like a crouch button - the character crouches only when the down arrow key is being HELD, not only pressed once. How do I make it work? Here is what I have tried but it doesn't work. Thanks in advance!!!!!

document.onkeydown = function (event) {
    let key = event.key;
    while (key ==  "ArrowDown") {
        character.style.width = 50 + "px";
        character.style.height = 30 + "px";
        character.style.top = 115 + "px";
    }
}

keydown event is continuously fired when you hold down any key and when you release the key, keyup event is fired.

To achieve what you are trying to do, add the styles to the character when keydown event is fired and on keyup event remove those styles from the character.

Following code snippet shows an example:

 const character = document.querySelector('.character'); document.body.addEventListener('keydown', (event) => { character.classList.add('crouch'); }); document.body.addEventListener('keyup', (event) => { character.classList.remove('crouch'); });
 div { width: 100px; height: 100px; background: yellow; position: relative; }.crouch { height: 50px; top: 50px; }
 <div class="character">Press any key</div>

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