jQuery set在第一次点击时超时,然后在第二次点击时清除超时



用户第一次单击按钮时,我希望在循环动画之前在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(); });
});

您需要在函数范围之外定义变量,以便以后可以清除它。此外,您正在清除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(); });
});

最新更新