← 中文资源

简体中文版本

Element.animate 驱动关键帧动画

animate() 立即开跑并返回 Animation 对象:playState 可暂停续播,finish() 直跳终点,finished 是 Promise,cancel() 会以 AbortError 拒绝它。

阅读英文原文

实现说明

每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。 演示用的数据放在这几个模块级绑定中:card、animation。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 跑完文件,输出里会留下标记——running :、paused :、finished:。

常见问题

「Element.animate 驱动关键帧动画」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

await animation.finished;

代码示例

// Web Animations API: animate() returns an Animation object you control.
const card = document.createElement('div');
document.body.append(card);

const animation = card.animate(
  [
    { transform: 'translateY(0)', opacity: 1 },
    { transform: 'translateY(-8px)', opacity: 0.6 },
    { transform: 'translateY(0)', opacity: 1 },
  ],
  { duration: 400, easing: 'ease-in-out', iterations: 2 }
);

console.log('running :', animation.playState); // 'running' immediately
animation.pause();
console.log('paused  :', animation.playState);
animation.play();

// finish() jumps to the very end: currentTime equals the full active duration.
animation.finish();
console.log('finished:', animation.playState, 'currentTime:', animation.currentTime);

// animation.finished is a promise; cancel() rejects it with an AbortError.
animation.cancel();
try {
  await animation.finished;
} catch (rejection) {
  console.log('rejected:', rejection.name);
}