用户第一次单击按钮时,我希望div在循环动画之前有一个3秒的超时设置。
如果用户在这3秒内再次单击,我希望超时清除,动画停止。
到目前为止,我可以让超时正常工作,但我不能清除它并让动画停止。
HTML:
<a href="#" class="button">Button</a>
<div class="block"></div>CSS:
div.block {
position: absolute;
display: block;
height: 100px;
width: 100px;
top: -10px;
left: 50%;
background-color: red; }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(); });
});发布于 2012-11-17 20:47:34
您需要在函数的作用域之外定义变量,以便以后可以清除它。此外,您正在清除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(); });
});https://stackoverflow.com/questions/13430671
复制相似问题