首页 > 解决方案 > 并排动画两个元素不起作用(淡入,淡出,动画)

问题描述

我正在尝试为两个元素设置动画。

http://jsfiddle.net/1tLfwrhg/

font {
  display: block;
}

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

<font id="test1" size="7">0000000000000000</font>
<font id="test2" size="7">0000000000000000</font>

$('#test1, #test2').fadeOut(500, function() {
  $('#test1, #test2').text('11111111111111111111')
  $('#test1, #test2').fadeIn(500)
  $('#test1, #test2').fadeOut(500, () => {
    $('#test1, #test2').text('2222222222222222');
    $('#test1, #test2').css("color", "green").addClass("red")
  })
  $('#test1, #test2').fadeIn(500)
  $('#test1, #test2').delay(500)
  $("#test1").animate({
    'margin-left': '150px'
  }, {
    duration: 100
  })
  $("#test2").animate({
    'margin-left': '300px'
  }, {
    duration: 1000
  })
  $('#test1, #test2').delay(1000)
  $('#test1, #test2').fadeOut(500)
});

一开始动画看起来不错。但最后我得到一个奇怪的眨眼,我不知道为什么......

标签: jquery

解决方案


首先,您可以将每个元素相同的所有fade和调用链接在一起。delay.text()调用放在fade回调中,例如:

const $tests = $('#test1, #test2');
$tests
  .fadeOut(500, () => {
    $tests.text('11111111111111111111')
  })
  .fadeIn(500)

然后,一旦两个元素的动作发散,分别调用.animate这两个元素,然后.promise()两者上都使用等待,直到集合中所有元素的所有动画都完全完成:

$("#test1").animate({
  'margin-left': '150px'
}, {
  duration: 100
})
$("#test2").animate({
  'margin-left': '300px'
}, {
  duration: 1000
});
$tests
  .promise()
  .done(() => {
    // all animations are done

在全:

const $tests = $('#test1, #test2');
$tests
  .fadeOut(500, () => {
    $tests.text('11111111111111111111')
  })
  .fadeIn(500)
  .fadeOut(500, () => {
    $('#test1, #test2').text('2222222222222222');
    $('#test1, #test2').css("color", "green").addClass("red")
  })
  .fadeIn(500)
  .delay(500);
$("#test1").animate({
  'margin-left': '150px'
}, {
  duration: 100
})
$("#test2").animate({
  'margin-left': '300px'
}, {
  duration: 1000
});
$tests
  .promise()
  .done(() => {
    $tests
      .delay(100)
      .fadeOut(500)
  })
font {
  display: block;
}

.red {
  font-size: 150%;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<font id="test1" size="7">0000000000000000</font>
<font id="test2" size="7">0000000000000000</font>


推荐阅读