我希望在用户按住按钮“x”秒后调用一个函数。请帮忙。
答案 0 :(得分:3)
调用setTimeout()以在3000毫秒后执行操作,将setTimeout()中的标识符存储到作用于函数上方的变量中。在元素的mouseup()上,如果存在超时,则通过clearTimeout()清除超时。
var divMouseDown;
$('#div-id').mousedown(function() {
divMouseDown = setTimeout(function() {
// Do timeout action...
}, 3000);
});
$('#div-id').mouseup(function() {
if (divMouseDown) {
clearTimeout(divMouseDown);
}
});
答案 1 :(得分:2)
(function () {
function someFunction()
{
alert("do something");
}
var x = 2000; // 2000 miliseconds = 2 seconds
var mousePressed = false;
var timePressed = 0;
var timeHolding = 0;
function check(){
timeHolding = new Date().getTime() - timePressed;
if(timeHolding >= x){
someFunction();
}
}
window.addEventListener('mousedown', function () {
if(!mousePressed){
mousePressed = true;
timePressed = new Date().getTime(); // or Date.now()
setTimeout(function(){ check() }, x);
}
}, false);
window.addEventListener('mouseup', function () {
mousePressed = false;
timePressed = new Date().getTime();
}, false);
})();
检查它是否有效here。
答案 2 :(得分:0)
$('div.target').primarydown( function() {
released = false;
$(this).primaryup( function() {
released = true;
});
setTimeout( function() {
if( released ) return;
else {
// call required function
}
}, 1000 /* timeout */ );
});