← 中文资源

简体中文版本

transitionend 报告结束的属性

CSS 过渡按属性逐个收尾:每个 transitionend 事件带出 propertyName 与 elapsedTime;中途打断则改发 transitioncancel 且不再有 end,收尾逻辑要两条路径都接住。

阅读英文原文

实现说明

panel 定义在模块顶层,中间不经过函数作用域。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 演示输出是带标签的(ended:、cancelled:),每个操作都会留下自己的一行标注。

常见问题

「transitionend 报告结束的属性」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

panel.addEventListener('transitioncancel', (event) => {
  console.log('cancelled:', event.propertyName);
});
panel.addEventListener('transitionend', (event) => {
  console.log('ended:', event.propertyName, 'after', event.elapsedTime, 's');
});

代码示例

const panel = document.querySelector('#panel');

// each property participating in the transition fires its own transitionend when it finishes
panel.addEventListener('transitionend', (event) => {
  console.log('ended:', event.propertyName, 'after', event.elapsedTime, 's');
});

// an interrupted transition (e.g. the class is removed midway) fires transitioncancel, and no end event follows
panel.addEventListener('transitioncancel', (event) => {
  console.log('cancelled:', event.propertyName);
});

// triggering the transition: add a class that changes width/opacity (a matching CSS transition definition is required)
panel.classList.add('open');