JS动画仅在依赖运行时数据、需逐帧控制、多元素联动或CSS无法实现特殊缓动时必要;优先用CSS transition/@keyframes或Element.animate(),手写requestAnimationFrame须处理取消、时间校准与跳帧保护。

requestAnimationFrame 是实现流畅 JavaScript 动画的核心,但多数场景下你其实不该手动写它——CSS transition 和 @keyframes 更轻量、更稳定、更省电。
什么时候该用 JS 动画,而不是 CSS?
JS 动画只在以下情况真正必要:
- 动画逻辑依赖运行时数据(比如鼠标位置、滚动进度、Canvas 像素值)
- 需要逐帧控制或中断/暂停/反向(
Element.animate()支持部分,但复杂交互仍需 JS) - 多个元素需按数据关系联动(如图表中 200 个柱状图随数组动态更新高度)
- CSS 无法表达的缓动函数(如基于物理的阻尼运动,需实时计算
easeOutCubic以外的曲线)
Element.animate() 能替代大部分传统 JS 动画循环
这是现代浏览器原生支持的 Web Animations API,比手写 requestAnimationFrame + setInterval 更可靠,且自动适配 CSS 属性和性能优化。
const box = document.querySelector('.box');
box.animate(
[
{ transform: 'translateX(0)', opacity: 1 },
{ transform: 'translateX(100px)', opacity: 0.5 }
],
{
duration: 300,
easing: 'ease-in-out',
fill: 'forwards'
}
);注意几个关键点:
立即学习“Java免费学习笔记(深入)”;
-
fill: 'forwards'必须显式设置,否则动画结束立刻回退到初始状态 - 不支持所有 CSS 属性(如
background-image、自定义属性--my-var需配合@property) - IE 完全不支持,Edge 79+ 才可用;如需兼容,用
anime.js或降级为transition
CSS transition 够用时,别碰 JS
只要动画是「状态切换」(如 hover、focus、class 切换),transition 几乎总是最优解:
.button {
background-color: #007bff;
transition: background-color 0.2s ease, transform 0.15s ease;
}
.button:hover {
background-color: #0056b3;
transform: scale(1.05);
}常见陷阱:
- 只写了
transition: all 0.3s—— 这会触发不必要的重排(layout),应精确指定属性名 - 动态添加 class 后立刻读取 offsetTop 等布局属性 —— 浏览器可能尚未应用 transition,需用
getComputedStyle或setTimeout(() => {}, 0)触发重排 -
transition对display: none ↔ block无效 —— 改用opacity+visibility+height组合
手写 requestAnimationFrame 的最小安全模式
真要自己写,必须处理三件事:取消机制、时间校准、跳帧保护。
let animationId = null; let startTime = null; const duration = 600;function animate(timestamp) { if (!startTime) startTime = timestamp; const progress = Math.min((timestamp - startTime) / duration, 1);
// 更新样式(避免 layout thrashing) element.style.transform =
translateX(${progress * 200}px);if (progress < 1) { animationId = requestAnimationFrame(animate); } }
// 启动 animationId = requestAnimationFrame(animate);
// 清理(比如组件卸载时) cancelAnimationFrame(animationId);
漏掉 cancelAnimationFrame 会导致内存泄漏和后台页面持续耗电。React/Vue 中务必在 useEffect 的 cleanup 或 beforeUnmount 里调用它。
CSS 过渡和动画的边界比想象中清晰:状态驱动选 CSS,数据/事件/物理驱动才上 JS。最常被忽略的是「过渡完成后的状态保持」——无论是 fill: forwards、transitionend 事件监听,还是 class 切换后的 DOM 状态清理,漏掉任何一个,动画就会在用户眼皮底下“抽搐”一下。










