第一次单击jQuery setTimeout,第二次单击clearTimeout
用户第一次单击按钮时,我希望在循环设置动画之前在div上设置3秒超时 如果用户在这3秒钟内再次单击,我希望清除超时并停止动画 到目前为止,我可以让超时正常工作,但我不能清除它,让动画停止 HTML:第一次单击jQuery setTimeout,第二次单击clearTimeout,jquery,animation,settimeout,Jquery,Animation,Settimeout,用户第一次单击按钮时,我希望在循环设置动画之前在div上设置3秒超时 如果用户在这3秒钟内再次单击,我希望清除超时并停止动画 到目前为止,我可以让超时正常工作,但我不能清除它,让动画停止 HTML: <a href="#" class="button">Button</a> <div class="block"></div> jQuery: $('a.button').toggle(function(){ var blockTimer;
<a href="#" class="button">Button</a>
<div class="block"></div>
jQuery:
$('a.button').toggle(function(){
var blockTimer;
blockTimer = setTimeout(function block(){
$("div.block").animate({top: '400px'}, 4000, 'linear', function() { $(this).css('top', '-10px'); block(); });
},3000);
}, function(){
clearTimeout(rainTimer);
$('div.block').clearQueue().stop().fadeOut(500, function() { $(this).css('top', '-10px').show(); });
});
您需要在函数范围之外定义变量,以便稍后清除它。此外,您正在清除
rainTimer
,但您将其定义为blockTimer
var blockTimer;
$('a.button').toggle(function(){
blockTimer = setTimeout(function block() {
$("div.block").animate({top: '400px'}, 4000, 'linear', function() { $(this).css('top', '-10px'); block(); });
}, 3000);
}, function() {
clearTimeout(blockTimer);
$('div.block').clearQueue().stop().fadeOut(500, function() { $(this).css('top', '-10px').show(); });
});
请把问题弄得一团糟啊,是的,当然!现在看来很明显。很抱歉,我打错了rainTimer,我的原始代码中的rainTimer是正确的。不过,这个答案是正确的。
var blockTimer;
$('a.button').toggle(function(){
blockTimer = setTimeout(function block() {
$("div.block").animate({top: '400px'}, 4000, 'linear', function() { $(this).css('top', '-10px'); block(); });
}, 3000);
}, function() {
clearTimeout(blockTimer);
$('div.block').clearQueue().stop().fadeOut(500, function() { $(this).css('top', '-10px').show(); });
});