如何检测在javascript中按下了x秒的按键? [英] How to detect a key pressed for x seconds in javascript?
本文介绍了如何检测在javascript中按下了x秒的按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检测用户何时持续按住X秒的按钮并调用JavaScript中的函数.你能指出我正确的方向吗?
I need to detect when a user keep press a button for X second and call function in JavaScript. Could you point me out in right direction?
推荐答案
You can use a setTimeout
function on the keydown
event which will fire after X seconds to compare the time that event was triggered to the last time a keyup
was triggered - if at all.
var lastKeyUpAt = 0;
$(elem).on('keydown', function() {
// Set key down time to the current time
var keyDownAt = new Date();
// Use a timeout with 1000ms (this would be your X variable)
setTimeout(function() {
// Compare key down time with key up time
if (+keyDownAt > +lastKeyUpAt)
// Key has been held down for x seconds
else
// Key has not been held down for x seconds
}, 1000);
});
$(elem).on('keyup', function() {
// Set lastKeyUpAt to hold the time the last key up event was fired
lastKeyUpAt = new Date();
});
elem
这是您要处理事件的元素.
elem
here is the element you're wanting to handle the event on.
这篇关于如何检测在javascript中按下了x秒的按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文