【问题标题】:jQuery setTimeout on first click then clearTimeout on secondjQuery setTimeout 在第一次点击然后 clearTimeout 在第二次
【发布时间】:2012-11-17 12:42:05
【问题描述】:

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

【问题讨论】:

  • 请做一个js小提琴问题

标签: jquery animation settimeout


【解决方案1】:

您需要在函数范围之外定义变量,以便稍后清除它。此外,您正在清除 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,我在原始代码中输入正确。不过这个答案是正确的。
猜你喜欢
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 2018-05-25
  • 1970-01-01
相关资源
最近更新 更多