如何在 jQuery 中创建链式延迟动画序列

How create a chained delayed animation sequence in jQuery?

本文关键字:延迟 动画 创建 jQuery      更新时间:2023-09-26

考虑具有以下对象:

<div id="d1"><span>This is div1</span></div>
<div id="d2"><span>This is div2</span></div>
<div id="d3"><span>This is div3</span></div>
<div id="d4"><span>This is div4</span></div>
<div id="clickhere"><span>Start animation</span></div>

考虑到我想使用 jQuery 在前面列出的四个元素中的每一个上应用动画。

我现在拥有的

如果页面,请考虑在 head 部分中应用的以下代码:

function start_anim() {
  $("#d1").animate({top:"-50px"},1000,function(){}); // Animating div1
  $("#d2").animate({top:"-50px"},1000,function(){}); // Animating div2
  $("#d3").animate({top:"-50px"},1000,function(){}); // Animating div3
  $("#d4").animate({top:"-50px"},1000,function(){}); // Animating div4
}
$(document).ready($('#clickhere').click(start_anim));

触发事件click时,此脚本片段将导致四个div 的同步转换。

我想要什么

但是,我想先进行第一个div 移动,然后当第一个div 的动画达到 50% 时,我想进行第二个div 移动。第三个和最后一个div 也是如此。

我怎样才能到达这个?谢谢

像这样:

$("#d1").animate({top:-50}, 1000);
$("#d2").delay(500).animate({top:-50}, 1000);
$("#d3").delay(1000).animate({top:-50}, 1000);
$("#d4").delay(1500).animate({top:-50}, 1000);

甚至更好:

var duration = 1000;
$('#d1,#d2,#d3,#d4').each(function(i) {
   $(this).delay( i*(duration/2) ).animate({top:-50}, duration);
});