admin管理员组文章数量:1336622
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";
}
}
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";
}
}
Share
Improve this question
edited Aug 13, 2020 at 6:04
Yousaf
29.4k6 gold badges51 silver badges75 bronze badges
asked Aug 13, 2020 at 5:34
pierrehpierreh
1691 silver badge8 bronze badges
2
-
you can handle the
onKeyDown
and OnKeyUp if there is no keyup event then it is held down. – liang.good Commented Aug 13, 2020 at 5:37 - The time between keydown and keyup events represent the duration of a key being held down. When you get the keydown, go into crouch mode and listen for a keyup to stop crouching. – ray Commented Aug 13, 2020 at 5:39
2 Answers
Reset to default 7keydown
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>
I think what you might be looking for is to simply put this at the beginning of the code block within the event listener:
if (!e.repeat) return
本文标签: javascriptHow to check if a key (on the keyboard) is being held downStack Overflow
版权声明:本文标题:javascript - How to check if a key (on the keyboard) is being held down? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742409513a2469502.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论