什么是 View Transition API
View Transition API 是 Chrome 推出的一项新特性,它允许开发者在 DOM 状态变化时创建平滑的过渡动画。与传统的 CSS 动画不同,它能够在页面元素变化前后捕获快照,并自动计算差异进行插值动画。
基础实现
首先,我们需要一个切换按钮和基本的样式结构:html
<button id="theme-toggle">切换模式</button>
:root {
--bg-color: #ffffff;
--text-color: #333333;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}添加 View Transition 动画
核心代码非常简单,只需要在切换主题时调用 document.startViewTransition:
const toggleBtn = document.getElementById('theme-toggle');
const html = document.documentElement;
toggleBtn.addEventListener('click', async (e) => {
// 检查浏览器是否支持 View Transition API
if (!document.startViewTransition) {
toggleTheme();
return;
}
// 获取点击位置,作为动画起点
const x = e.clientX;
const y = e.clientY;
// 创建圆形扩散动画
const transition = document.startViewTransition(() => {
toggleTheme();
});
await transition.ready;
// 自定义动画效果
const clipPath = [
`circle(0% at ${x}px ${y}px)`,
`circle(150% at ${x}px ${y}px)`
];
document.documentElement.animate({
clipPath: html.dataset.theme === 'dark' ? clipPath.reverse() : clipPath
}, {
duration: 500,
easing: 'ease-in-out',
pseudoElement: '::view-transition-new(root)'
});
});
function toggleTheme() {
const currentTheme = html.dataset.theme;
html.dataset.theme = currentTheme === 'dark' ? 'light' : 'dark';
}进阶技巧
1. 为特定元素添加独立过渡css
::view-transition-old(header),
::view-transition-new(header) {
animation-duration: 0.3s;
}2. 处理不支持 API 的浏览器
if (!document.startViewTransition) { // 降级方案:使用普通 CSS 过渡 toggleTheme();}3. 性能优化
View Transition API 会自动处理大部分性能优化,但我们应该避免在过渡期间执行复杂计算。
浏览器兼容性
目前 View Transition API 在 Chrome 111+ 和 Edge 111+ 中得到支持。对于其他浏览器,建议提供渐进增强方案。
总结
View Transition API 极大地简化了复杂页面过渡动画的实现。通过简单的几行代码,我们就能为日夜模式切换添加专业级的动画效果。随着浏览器支持度的提升,这项技术必将成为 Web 动画的标准方案。