首页 > 解决方案 > 链接淡入、淡出、动画、错误的执行顺序

问题描述

我正在尝试以编程方式更改一些文本,添加一个类,对其进行动画处理。到目前为止,我有这个代码:

.red {
  font-size: 150%;
  color: red;
}

<font id="test" size="7">0000000000000000</font>

$('#test').fadeOut(500, function() {
  const $this = $(this);
  $this.text('11111111111111111111')
      .fadeIn(500)
      .fadeOut(500, () => $this.text('2222222222222222')
          .css("color", "green"))
          .addClass("red")
          .fadeIn(500)
          .animate({'margin-left': '250px'}, {duration: 3000, complete: function(){
                                    $this.fadeOut(200)
                                }
                              })
});

不幸的是,订单似乎搞砸了。“red”类被添加到文本“1111111.....”而不是文本“222222....”中,我不明白为什么。

这里是 jsFiddle:http: //jsfiddle.net/3nus4wpy/2/

标签: javascriptjqueryhtml

解决方案


您必须将要在淡入淡出时发生的所有异步(除了进一步淡入淡出)放在淡入淡出回调中:

$('#test').fadeOut(500, function() {
  const $this = $(this);
  $this.text('11111111111111111111')
    .fadeIn(500)
    .fadeOut(500, () => {
      $this.text('2222222222222222');
      $this
        .css("color", "green")
        .addClass("red")
    })
    .fadeIn(500, () => {
      $this.animate({
        'margin-left': '250px'
      }, {
        duration: 3000,
        complete: function() {
          $this.fadeOut(200)
        }
      });
    });
});
.red {
  font-size: 150%;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<font id="test" size="7">0000000000000000</font>

您还可以调用delay以在下一个链式函数运行之前创建延迟,例如:

$('#test').fadeOut(500, function() {
  const $this = $(this);
  $this.text('11111111111111111111')
  .fadeIn(500)
  .fadeOut(500, () => {
    $this.text('2222222222222222');
    $this.css("color", "green").addClass("red")
  })
  .fadeIn(500)
  .delay(500)
  .animate({
      'margin-left': '250px'
    }, {
      duration: 3000
  })
  .delay(3000)
  .fadeOut(5500)
});
.red {
  font-size: 150%;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<font id="test" size="7">0000000000000000</font>


推荐阅读