教程 animejs tutorial

控制时间轴顺序与嵌套

Anime.js 的时间轴功能非常强大,除了基本的顺序执行,还支持复杂的时间控制与嵌套,方便你打造多层次的动画效果。

顺序控制

使用时间轴的 add() 方法时,可以通过第二个参数控制动画的开始时间:

  • 相对时间:例如 '-=500' 表示提前 500ms 开始
  • 绝对时间:指定精确的开始时间(毫秒)
js
const tl = anime.timeline({
  easing: "easeOutQuad",
  duration: 800,
});

tl.add({ targets: ".box1", translateX: 250 })
  .add({ targets: ".box2", translateY: 50 }, "-=400") // 与前一个动画重叠400ms
  .add({ targets: ".box3", opacity: 0.5 }, 1000); // 绝对时间1秒后开始

嵌套时间轴

时间轴可以嵌套,允许将一个时间轴作为另一个时间轴的动画目标,实现更复杂的动画管理:

js
const childTl = anime.timeline();
childTl.add({ targets: ".box2", rotate: "1turn" });

const parentTl = anime.timeline();
parentTl.add({ targets: ".box1", translateX: 200 }).add(childTl, "-=300"); // 嵌套子时间轴

小结

通过灵活的时间参数和嵌套机制,可以精确控制动画的顺序与层级,打造高质量交互动画。

示例演示

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Anime.js 时间轴顺序与嵌套示例</title> <style> .box1, .box2, .box3 { width: 50px; height: 50px; margin: 10px; display: inline-block; border-radius: 5px; user-select: none; }

.box1 {
  background-color: #4FC08D;
}

.box2 {
  background-color: #F67280;
}

.box3 {
  background-color: #355C7D;
}

#startBtn {
  display: block;
  margin: 20px auto;
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 6px;
  border: none;
  background-color: #4FC08D;
  color: white;
  transition: background-color 0.3s;
}

#startBtn:hover {
  background-color: #3a9d6f;
}

</style> </head>

<body> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div>

<button id="startBtn">点击开始动画</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js&quot;&gt;&lt;/script&gt; <script> var childTl = anime.timeline({ autoplay: false }); childTl.add({ targets: ‘.box2’, rotate: ‘1turn’, duration: 1000 });

var parentTl = anime.timeline({
  autoplay: false
});
parentTl
  .add({
    targets: '.box1',
    translateX: 200,
    duration: 1000
  })
  .add(childTl, '-=300');

document.getElementById('startBtn').onclick = function () {
  parentTl.restart();
};

</script> </body>

</html>