我想补充一个每毫秒,如果用户使长mousepress和10停止,+1长期鼠标按下和每100ms停在10
类似的东西?
$('#bar').mousedown(function(){
setInterval(function() {
for(i=1; i<11; i++){
$('#foo').val(i);
}
}, 100);
});
的jsfiddle:http://jsfiddle.net/9qeeg/
我想补充一个每毫秒,如果用户使长mousepress和10停止,+1长期鼠标按下和每100ms停在10
类似的东西?
$('#bar').mousedown(function(){
setInterval(function() {
for(i=1; i<11; i++){
$('#foo').val(i);
}
}, 100);
});
的jsfiddle:http://jsfiddle.net/9qeeg/
你可以我们可以使用clearInterval()和清除时mouseUp事件或当您达到10
var intVal = null;
var cnt = 0;
$('#bar').on('mousedown', function() {
intVal = setInterval(function() {
$('#foo').val(cnt);
cnt == 10 ? clearInterval(intVal) : cnt++;
}, 100);
}).on('mouseup', function() {
clearInterval(intVal);
if (cnt == 10) {
cnt = 0
}
});
重构一个位,以避免使用超时和间隔:
var mouse = {
interval:null, // reference to setInterval
count: 0 // count
};
// on mouse down, set an interval to go off every 100 ms. Every
// execution of this interval increases the counter by one.
// however, clear the interval (automatically) after 1000ms (100ms * 10)
$('#bar').on('mousedown', function(){
// reset count (Can also fetch it from the input box if you'd like)
mouse.count = 0;
// establish interval that will run 10 times (with 100ms delay)
mouse.interval = setInterval(function(){
// increase count and place new value in the text field
$('#foo').val(++mouse.count);
// stop interval automatically when it reaches 10
if (mouse.count == 10) {
clearInterval(mouse.interval);
}
}, 100);
});
// Stop interval
// bind to the document to if the user's mouse strays from the button
// we still catch the event
$(document).on('mouseup', function(){
if (mouse.interval){
clearInterval(mouse.interval);
mouse.interval = null;
}
});
旧版本:
var mouse = {
interval:null, // reference to setInterval
timeout:null, // reference to setTimeout
count: 0 // count
};
// on mouse down, set an interval to go off every 100 ms. Every
// execution of this interval increases the counter by one.
// however, clear the interval (automatically) after 1000ms (100ms * 10)
$('#bar').on('mousedown', function(){
mouse.count = 0;
mouse.interval = setInterval(function(){
$('#foo').val(++mouse.count);
}, 100);
mouse.timeout = setTimeout(function(){
clearInterval(mouse.interval);
}, 100 * 10);
});
// Stop interval
// bind to the document to if the user's mouse strays from the button
// we still catch the event
$(document).on('mouseup', function(){
mouse.interval && clearInterval(mouse.interval), mouse.interval = null;
mouse.timeout && clearTimeout(mouse.timeout), mouse.timeout = null;
});
您更新小提琴:http://jsfiddle.net/9qeeg/5/
太棒了!但重新在clic上重新开始? – Muramasa
@muramasa:如果您不希望重新启动,请在符合条件时在mousedown事件中添加逻辑,以停止事件的其余部分(带间隔和超时的部分)。 –
你们是不是要做出对mousepress启动计时器和数到10? –
我试着制作一个自动添加的脚本,因为它考虑了#foo的启动值,并且每100毫秒添加一个不要指定10的时间到10 – Muramasa