简体   繁体   English

如何检查一个键(在键盘上)是否被按住?

[英]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.我需要一个 function,它的工作原理有点像蹲伏按钮 - 角色只有在按住向下箭头键时才会蹲伏,而不仅仅是按下一次。 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.当您按住任何键时, keydown事件会持续触发,当您释放键时,会触发keyup事件。

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.要实现您想要做的事情,请在触发keydown事件时将 styles 添加到角色,并在keyup事件中从角色中删除这些 styles。

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>

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

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