教程 animejs tutorial

动态属性设置

Anime.js 支持通过函数动态计算动画属性值,这使得动画可以根据当前元素状态、索引或其他参数灵活变化。

通过函数动态设置属性

属性值可以是函数,函数接受三个参数:

  • el 当前元素
  • i 当前元素的索引
  • t 当前动画实例

函数应返回动画属性的最终值。

js
anime({
  targets: ".box",
  translateX: (el, i) => 50 + i * 30,
  rotate: (el, i) => i * 45,
  duration: 1000,
});

示例

上例中,多个 .box 元素会依次向右移动且旋转角度递增,实现错落有致的动画效果。

应用场景

  • 基于元素索引设置动画差异
  • 动态根据元素属性计算动画值
  • 结合复杂逻辑实时调整动画参数

小结

动态属性设置极大提升了动画的灵活度,配合函数回调能创造丰富多变的视觉效果。

示例演示

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

<head> <meta charset="UTF-8" /> <title>Anime.js 动态属性设置示例</title> <style> .box { width: 50px; height: 50px; background-color: #4FC08D; margin: 10px; display: inline-block; border-radius: 6px; user-select: none; color: white; line-height: 50px; text-align: center; font-weight: bold; }

#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="box">1</div> <div class="box">2</div> <div class="box">3</div> <div class="box">4</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 animation; document.getElementById(‘startBtn’).onclick = function () { animation = anime({ targets: ‘.box’, translateX: function (el, i) { return 50 + i * 30; }, rotate: function (el, i) { return i * 45; }, duration: 1000, easing: ‘easeInOutSine’ }); }; </script> </body>

</html>