教程 animejs tutorial

推荐属性与替代方案

动画性能在开发中至关重要。选择合适的 CSS 属性不仅能提升动画流畅度,还能减少页面卡顿。以下为推荐和不推荐使用的属性对比及替代方案。

1. 推荐使用的高性能属性(GPU 加速)

属性 说明
transform 位移(translateX/Y/Z)、缩放(scale)、旋转(rotate)等,利用 GPU 加速
opacity 透明度变化,常用且性能好
filter 部分滤镜效果支持硬件加速

使用这些属性能避免触发布局重排和重绘,提升动画效率。

2. 避免使用的低效属性

属性 问题 替代方案
width、height 修改会触发布局回流,影响性能 使用 scaleX、scaleY 缩放替代
top、left 触发布局变化 使用 translateX、translateY 替代
margin 可能引起布局重绘 使用位移动画替代

3. 替代示例

将宽度变化动画替换为缩放动画,提高性能表现:

js
// 不推荐(触发布局)
anime({
  targets: ".box",
  width: "200px",
  duration: 1000,
});

// 推荐(GPU 加速)
anime({
  targets: ".box",
  scaleX: 2,
  duration: 1000,
});

动画对比演示

通过下面的示例,可以直观看到使用 transform 和 width 的动画效果差异。

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

<head> <meta charset="UTF-8" /> <title>推荐属性与替代方案示例</title> <style> body { font-family: sans-serif; text-align: center; padding: 40px; background: #fafafa; }

.container {
  display: flex;
  justify-content: center;
  gap: 80px;
  margin-top: 30px;
}

.box {
  width: 80px;
  height: 80px;
  background-color: #4FC08D;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  user-select: none;
}

.box.bad {
  background-color: #F67280;
}

button {
  margin-top: 20px;
  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;
}

.label {
  margin-top: 10px;
  font-weight: 600;
}

</style> </head>

<body>

<h2>推荐属性(左) vs 不推荐属性(右)动画演示</h2>

<div class="container"> <div> <div class="box good">推荐</div> <div class="label">transform + opacity</div> </div> <div> <div class="box bad">不推荐</div> <div class="label">width + opacity</div> </div> </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 btn = document.getElementById(‘startBtn’); const goodBox = document.querySelector(‘.box.good’); const badBox = document.querySelector(‘.box.bad’);

  btn.addEventListener('click', function () {
    // 推荐动画,使用 transform 和 opacity (GPU加速)
    anime({
      targets: goodBox,
      translateX: 200,
      opacity: 0.5,
      duration: 1500,
      easing: 'easeInOutSine',
      direction: 'alternate',
      loop: 2
    });

    // 不推荐动画,使用 width 和 opacity(会触发布局)
    anime({
      targets: badBox,
      width: 160,
      opacity: 0.5,
      duration: 1500,
      easing: 'easeInOutSine',
      direction: 'alternate',
      loop: 2
    });

    btn.disabled = true;
    btn.textContent = &quot;动画进行中...&quot;;
  });
})()

</script>

</body>

</html>