← 中文资源

简体中文版本

animationend 让一次性动画自动退场

用 animationend 代替猜时长:CSS 管动画节奏,JS 监听结束事件后移除节点并用 removeEventListener 清理监听,animationcancel 兜住动画被中断的出口。

阅读英文原文

实现说明

底层就是函数 retire。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 守卫 event.target !== toast 满足时靠提前的 return 短路流程。
  • 直接运行文件,输出会带上标签,比如 toast removed by animationend:——输出的每一行都能指回产生它的那次调用。

常见问题

「animationend 让一次性动画自动退场」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

主要签名是 function retire(event)

核心语句

toast.addEventListener('animationcancel', retire);
toast.addEventListener('animationend', retire);
setTimeout(() => {
  console.log('toast removed by animationend:', removed);
}, 250);

代码示例

// CSS keeps the timing; JS just listens for the moment it finishes.
// .toast { animation: slide-in 180ms ease-out; }
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = 'Deploy started';
document.body.append(toast);

let removed = false;

function retire(event) {
  if (event.target !== toast) return; // child animations bubble up
  removed = true;
  toast.removeEventListener('animationend', retire);
  toast.remove();
}

// Fires when the toast's own animation completes — no setTimeout guesswork.
toast.addEventListener('animationend', retire);

// animationcancel covers the other exit: element hidden or animation aborted.
toast.addEventListener('animationcancel', retire);

setTimeout(() => {
  console.log('toast removed by animationend:', removed);
}, 250);