← 中文资源

简体中文版本

getAnimations 找到运行中的 CSS 过渡

element.getAnimations 枚举元素上活跃的 CSS 过渡(subtree: true 还会收集后代),用动画的 finished Promise 等待结束,替代猜时长的 setTimeout;但快照必须在新样式渲染完一帧之后取——改样式同帧就取只会拿到空列表。

阅读英文原文

实现说明

getAnimations 找到运行中的 CSS 过渡的核心是函数 nextFrame、waitForTransitions。 await 标出每个异步边界——没有 fire-and-forget。 返回新建的值,入参维持原状。

使用要点

  • 浏览器才是这里的运行环境:document、requestAnimationFrame 在 Node 里拿不到。
  • 每一步打印都带着自己的标签:running:、opacity settled:、later snapshot:。

常见问题

nextFrame 会修改传入的参数吗?

不会。代码构造并返回新值,入参保持原样,对共享或冻结的数据结构调用是安全的。

「getAnimations 找到运行中的 CSS 过渡」能在裸 Node.js 里跑吗?

不能——document、requestAnimationFrame 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

主签名形如 function nextFrame()

核心语句

return new Promise((resolve) => requestAnimationFrame(resolve));
return Promise.all(running.map((a) => a.finished));
.then(() => {
  panel.style.opacity = '1';
  return nextFrame();
})

代码示例

// CSS on the element: transition: opacity 240ms ease;
const panel = document.createElement('div');
panel.style.width = '40px';
panel.style.height = '40px';
panel.style.transition = 'opacity 240ms ease';
panel.style.opacity = '0';
document.body.append(panel);

function nextFrame() {
  return new Promise((resolve) => requestAnimationFrame(resolve));
}

function waitForTransitions(el) {
  // getAnimations({ subtree: true }) also collects descendant animations
  const running = el.getAnimations({ subtree: true });
  console.log('running:', running.map((a) => a.constructor.name || a.playState));
  return Promise.all(running.map((a) => a.finished));
}

// A CSS transition only exists once the browser has (1) rendered the old
// value and (2) put the new value through style recalc. Calling
// getAnimations earlier — same frame, or before the change is rendered —
// returns an empty list and Promise.all resolves immediately.
// Frame 1 paints the panel at opacity 0; frame 2 carries the change (the
// transition starts in that frame's style recalc); frame 3 is the first
// moment the snapshot reliably sees the running CSSTransition.
nextFrame()
  .then(() => nextFrame())
  .then(() => {
    panel.style.opacity = '1';
    return nextFrame();
  })
  .then(() => waitForTransitions(panel))
  .then(() => {
    console.log('opacity settled:', getComputedStyle(panel).opacity);
  });

setTimeout(() => {
  // By now the 240ms transition is done; a new snapshot finds none.
  console.log('later snapshot:', panel.getAnimations().length === 0);
}, 400);