Javascript 每隔0.2s运行mousedown事件,直到鼠标向上移动
当用户单击按钮时,我试图连续地向文本输入字段的值添加+1 简而言之,我的JQuery代码如下:Javascript 每隔0.2s运行mousedown事件,直到鼠标向上移动,javascript,jquery,mouseevent,settimeout,Javascript,Jquery,Mouseevent,Settimeout,当用户单击按钮时,我试图连续地向文本输入字段的值添加+1 简而言之,我的JQuery代码如下: $('#button').on({ mousedown : function () { var value = $(this).val(); $(this).val(value + 1); }, mouseup : function () { //Some other stuff here } }); 每次用户单击按钮时,此功能都会起作用。 我想要的是,如果用户一直按下按钮,mouse
$('#button').on({
mousedown : function () {
var value = $(this).val();
$(this).val(value + 1);
},
mouseup : function () {
//Some other stuff here
}
});
每次用户单击按钮时,此功能都会起作用。
我想要的是,如果用户一直按下按钮,mousedown事件每隔0.2s触发一次,直到他停止按下,然后mouseup事件触发
我想这应该通过setTimeout来完成,但如果有人告诉我怎么做,我会很高兴。谢谢。使用设置间隔和清除间隔:
但是,不可能每0.2毫秒运行一次,我想您的意思是每0.2秒运行一次…使用setInterval和clearInterval:
但是,不可能每0.2毫秒运行一次,我想您的意思是每0.2秒运行一次…您可以在鼠标按下代码后重复该事件
var int = null;
$("#button").mousedown(function() {
// Start the timer on mousedown
int = setInterval(function() {
$("#button").val($("#button").val() + 1);
}, 2);
}).mouseup(function() {
// Stop the timer after mouse up
clearInterval(int);
int = null;
// Other code
});
您可以使用在mousedown代码之后重复事件
var int = null;
$("#button").mousedown(function() {
// Start the timer on mousedown
int = setInterval(function() {
$("#button").val($("#button").val() + 1);
}, 2);
}).mouseup(function() {
// Stop the timer after mouse up
clearInterval(int);
int = null;
// Other code
});
你可以这样做:
$('#button').on({
mousedown: function () {
$(this).data('clicked', true);
var self = this;
var process = function() {
if ($(self).data('clicked')) {
console.log("process...");
setTimeout(process, 200);
}
};
process();
},
mouseup: function () {
$(this).data('clicked', false);
}
});
你可以这样做:
$('#button').on({
mousedown: function () {
$(this).data('clicked', true);
var self = this;
var process = function() {
if ($(self).data('clicked')) {
console.log("process...");
setTimeout(process, 200);
}
};
process();
},
mouseup: function () {
$(this).data('clicked', false);
}
});
事实上,你的解决方案比我的好-事实上,你的解决方案比我的好-Pevery 0.2ms,现在速度很快!每0.2毫秒,现在速度很快!