[英]Detecting duration of key-press using JavaScript
I'm very new to JavaScript, sorry if this is a dumb question, I haven't been able to find a good answer online.我对 JavaScript 很陌生,很抱歉,如果这是一个愚蠢的问题,我无法在网上找到好的答案。
I'm currently using:我目前正在使用:
document.body.addEventListener("keydown", function(e) { keys[e.keyCode] = true; });
document.body.addEventListener("keyup", function(e) { keys[e.keyCode] = false; });
to detect user input, which works quite well for my purpose, but I can't think of a good way to figure out how long a key has been pressed down.检测用户输入,这对我的目的来说非常有效,但我想不出一个好方法来确定一个键被按下了多长时间。
I've tried putting a while-loop that exits if keys[index]
returns false and increments a counter in the loop, but that just seems to break the script.我试过放置一个 while 循环,如果
keys[index]
返回 false 并在循环中增加一个计数器,则该循环将退出,但这似乎破坏了脚本。 I'm guessing I could write a function that specifically detects if the key I want has been released, but I'm not sure how to go about that properly.我猜我可以编写一个函数来专门检测我想要的密钥是否已被释放,但我不确定如何正确地进行。
Additionally, I only need to check it for one key.此外,我只需要检查一个键。
Instead of setting boolean values, set a timestamp on keydown, then retrieve it and compare against the current timestamp on keyup:不是设置布尔值,而是在 keydown 上设置时间戳,然后检索它并与 keyup 上的当前时间戳进行比较:
const signalKeypressDuration = (key, duration) => { console.log(`Key ${key} pressed for ${duration} ms`); }; const keys = {}; document.body.addEventListener("keydown", ({ key }) => { if (!keys[key]) keys[key] = Date.now(); }); document.body.addEventListener("keyup", ({ key }) => { signalKeypressDuration(key, Date.now() - keys[key]); keys[key] = null; });
Instead of putting in true
in keydown
, put new Date()
.而不是在
keydown
中输入true
,而是输入new Date()
。 Instead of putting in false
in keyup
, calculate new Date() - keys[e.keyCode]
and store it somewhere.不要在
keyup
中输入false
,而是计算new Date() - keys[e.keyCode]
并将其存储在某处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.