实现说明
panel、toggle 定义在模块顶层,中间不经过函数作用域。
使用要点
- 这是浏览器侧代码——
document在 Node 里解析不到。 - 每一步打印都带着自己的标签:
panel collapsed:。
常见问题
「startViewTransition 交叉淡入 DOM 更新」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。
核心语句
transition.finished.then(() => {
console.log('panel collapsed:', panel.classList.contains('collapsed'));
});
const transition = document.startViewTransition(() => {
panel.classList.toggle('collapsed');
});
代码示例
// document.startViewTransition snapshots the current DOM, runs the
// update callback, snapshots the result, and cross-fades the two —
// the animation itself comes from view transition pseudo-elements
const panel = document.querySelector('#panel');
const toggle = document.querySelector('#toggle');
toggle.addEventListener('click', () => {
// Reduced motion: skip the transition and mutate directly
if (matchMedia('(prefers-reduced-motion: reduce)').matches) {
panel.classList.toggle('collapsed');
return;
}
const transition = document.startViewTransition(() => {
panel.classList.toggle('collapsed');
});
// finished resolves when the cross-fade completes or is skipped
transition.finished.then(() => {
console.log('panel collapsed:', panel.classList.contains('collapsed'));
});
});