【问题标题】:Need help implementing the sequencing of jquery instructions需要帮助实现jquery指令的排序
【发布时间】:2013-05-29 18:43:06
【问题描述】:

问题:我有一个简单的函数,我需要其中的指令一次执行一个。这里是:

showImages = (current_time, exercise) ->
  $('#slideshow img.active').first().fadeOut(500).removeClass('active')
  $('#new-image').addClass('active')

由于最后两行几乎同时发生,id 为 'new-image' 的图像会淡出。

我希望在下一行开始之前完成处理带有“活动”类的 img 的行。

我已经进行了很多 Google 搜索,但我不知道如何将代码示例应用到这个用例中。以下是我找到的一些 Google 文章:

非常感谢您的帮助。

【问题讨论】:

  • “由于最后两行几乎同时发生,id 为 'new-image' 的图像会淡出。” - 这没有意义。 $('#slideshow img.active').first().fadeOut(500).removeClass('active') 行选择第一个img.active 元素(在#slideshow 内)并在其上排队一个fadeOut,然后立即删除其'active' 类。 fadeOut 需要 500 毫秒,但将 应用于该元素,它不会以某种方式也应用于其他可能在淡入淡出时添加了 'active' 类的元素。
  • P.S.您是否还有其他代码没有显示?

标签: javascript jquery coffeescript


【解决方案1】:

jQuery 的 fadeOut() method 有一个 complete 回调,可以用作函数:

.fadeOut( [duration ] [, complete ] )

这可以用作:

$(elem).fadeOut(500, function() { ... });

因此,在您的情况下,您可以简单地:

$('#slideshow img.active').first().fadeOut(500, function() {
    $(this).removeClass('active');
    $('#new-image').addClass('active');
});

这样,当前的.active 元素将失去其类,而#new-image 将在fadeOut() 完成后获得活动类

【讨论】:

    【解决方案2】:

    使用fadeOut()完成函数:

    $('#slideshow img.active').first().fadeOut(500, function() {
      $(this).removeClass('active');
      $('#new-image').addClass('active');
    });
    

    complete 函数中的任何代码都会在动画完成后执行

    【讨论】:

      【解决方案3】:

      试试这个希望这会有所帮助。这是一个快速的jsFiddle

          $('#slideshow img.active').first()
          .fadeOut(500).removeClass('active')
          .setTimeout(function(){
            $('#new-image').addClass('active')
          },100);
      

      【讨论】:

      • 谢谢刘易斯。我喜欢使用另一个答案来避免走 setTimeout 路。
      最近更新 更多