Animation API
简介
Animation API 是 Web Animations API 的一部分,允许开发者通过 JavaScript 精细控制 CSS 动画。它可以让你动态创建、播放、暂停、反转和销毁动画。
核心对象是 Animation,通常由 Element.animate() 方法返回。
element.animate 的参数详解
element.animate(keyframes, options) 方法用于创建并启动动画。它有两个参数:
1. keyframes(关键帧)
- 类型:
Array<Object>或Object - 用于描述动画过程中属性的变化。
数组写法(常用):
const animation = element.animate([
{ opacity: 0, transform: "translateY(0px)" }, // 起始状态
{ opacity: 1, transform: "translateY(100px)" }, // 结束状态
]);对象映射写法:
element.animate({
opacity: [0, 1],
transform: ["translateY(0px)", "translateY(100px)"],
});关键帧对象可选属性:
offset:取值 0~1,表示该帧在动画中的进度百分比。easing:为该帧设置单独的缓动函数(如 'ease-in'、'linear')。
示例:
const animation = element.animate([
{ opacity: 0, offset: 0 },
{ opacity: 1, offset: 0.5 },
{ opacity: 0.5, offset: 1 },
]);2. options(动画选项)
- 类型:
Object或Number - 用于控制动画的时长、循环次数等。
常用属性如下:
| 属性 | 类型 | 说明 |
|---|---|---|
| duration | Number | 动画时长(毫秒) |
| delay | Number | 动画延迟(毫秒) |
| endDelay | Number | 动画结束后的延迟(毫秒) |
| iterations | Number | 动画循环次数(默认 1,Infinity 表示无限循环) |
| direction | String | 动画方向('normal'、'reverse'、'alternate'、'alternate-reverse') |
| fill | String | 动画填充模式('none'、'forwards'、'backwards'、'both'、'auto') |
| easing | String | 动画整体缓动函数(如 'linear'、'ease-in'、'ease-out'、'cubic-bezier(…)') |
| composite | String | 关键帧合成方式('replace'、'add'、'accumulate'、'auto') |
示例:
const animation = element.animate(
[
{ opacity: 0, transform: "scale(0.5)" },
{ opacity: 1, transform: "scale(1)" },
],
{
duration: 1000,
delay: 200,
iterations: 3,
direction: "alternate",
fill: "forwards",
easing: "ease-in-out",
}
);更多详细内容可参考 MDN 文档。
基本用法
创建动画
const element = document.querySelector(".box");
const animation = element.animate(
[
{ transform: "translateX(0px)", opacity: 1 },
{ transform: "translateX(100px)", opacity: 0.5 },
],
{
duration: 1000, // 动画时长 1 秒
iterations: 2, // 播放 2 次
direction: "alternate", // 往返播放
}
);常用属性和方法
animation.play():播放动画animation.pause():暂停动画animation.reverse():反转动画方向animation.cancel():取消动画并重置到初始状态animation.finish():直接跳到动画结束状态animation.currentTime:当前动画时间(可读写)animation.playState:动画当前状态(如 running、paused、finished)
事件监听
可以监听动画的生命周期事件:
animation.onfinish = () => {
console.log("动画结束");
};示例:点击按钮控制动画
<button id="play">播放</button>
<button id="pause">暂停</button>
<div class="box" style="width:50px;height:50px;background:#09f;"></div>
<script>
const box = document.querySelector(".box");
const animation = box.animate([{ transform: "scale(1)" }, { transform: "scale(1.5)" }], {
duration: 1000,
fill: "forwards",
});
document.getElementById("play").onclick = () => animation.play();
document.getElementById("pause").onclick = () => animation.pause();
</script>注意事项
- Animation API 兼容性较好,但在部分旧版浏览器可能不支持全部特性,建议查阅 MDN 兼容性表。
- 动画对象不会自动销毁,长时间存在的动画建议调用
cancel()释放资源。 - 可以结合
requestAnimationFrame或 CSS 动画实现更复杂的效果。