教程 animejs tutorial

结合 CSS 动画使用

Anime.js 和 CSS 动画各有优劣。结合使用可以让动画既有良好性能,又方便管理和复用。

1. 何时使用 CSS 动画

  • 简单的过渡和循环动画。
  • 需要通过类名控制的状态切换。
  • 利用浏览器优化,性能更佳。

2. 何时使用 Anime.js

  • 复杂的序列动画和事件控制。
  • 动态生成动画参数。
  • 需要精确控制动画时序。

3. 结合使用示例

通过 Anime.js 触发 CSS 动画类切换,完成复杂效果。

html
<div class="box"></div>
<button id="startBtn">开始动画</button>

<style>
  .box {
    width: 100px;
    height: 100px;
    background: #4fc08d;
    border-radius: 10px;
    margin: 20px auto;
    transition: transform 0.5s ease;
  }

  .rotate {
    animation: rotate360 2s linear infinite;
  }

  @keyframes rotate360 {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>

<script>
  const box = document.querySelector(".box");
  const btn = document.getElementById("startBtn");

  btn.addEventListener("click", () => {
    anime({
      targets: box,
      translateY: 100,
      duration: 1000,
      easing: "easeInOutQuad",
      complete: () => {
        box.classList.add("rotate");
      },
    });
  });
</script>

4. 优势总结

  • CSS 动画高效且易管理。
  • Anime.js 适合动态控制和复杂时序。
  • 结合使用更灵活,提升体验。

代码示例

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

<head> <meta charset="UTF-8" /> <title>结合 CSS 动画使用示例</title> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 40px; background: #fafafa; }

.box {
  width: 100px;
  height: 100px;
  background: #4fc08d;
  border-radius: 10px;
  margin: 20px auto;
}

.rotate {
  animation: rotate360 2s linear infinite;
}

@keyframes rotate360 {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

button {
  margin-top: 30px;
  padding: 10px 24px;
  font-size: 16px;
  cursor: pointer;
  border: none;
  border-radius: 6px;
  background-color: #4fc08d;
  color: white;
  transition: background-color 0.3s;
}

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

</style> </head>

<body>

<div class="box"></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> (function () { const box = document.querySelector(‘.box’); const btn = document.getElementById(‘startBtn’);

  btn.addEventListener('click', () =&gt; {
    anime({
      targets: box,
      translateY: 100,
      duration: 1000,
      easing: 'easeInOutQuad',
      complete: () =&gt; {
        box.classList.add('rotate');
      }
    });
  });
})();

</script>

</body>

</html>