AI 文章摘要
XinruiGPT
加载中...
此内容根据文章生成,并未经过人工审核,仅用于文章内容的解释与总结

前言

最近在访问网站的过程,有个网站是呢喃Ninc,发现它切换日夜模式就会有过渡动画。

所以就询问群里的人,果然有大佬给了我一个地址,https://vitepress.dev/zh/guide/extending-default-theme#on-appearance-toggle

于是就配合AI给自己网站添加了过渡动画。

下面就是关于View Transition API的一些介绍。

什么是 View Transition API

View Transition API 是 Chrome 推出的一项新特性,它允许开发者在 DOM 状态变化时创建平滑的过渡动画。与传统的 CSS 动画不同,它能够在页面元素变化前后捕获快照,并自动计算差异进行插值动画。

基础实现

首先,我们需要一个切换按钮和基本的样式结构:

1
<button id="theme-toggle">切换模式</button>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
: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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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. 为特定元素添加独立过渡

1
2
3
4
::view-transition-old(header),
::view-transition-new(header) {
animation-duration: 0.3s;
}

2. 处理不支持 API 的浏览器

1
2
3
4
if (!document.startViewTransition) {
// 降级方案:使用普通 CSS 过渡
toggleTheme();
}

3. 性能优化

View Transition API 会自动处理大部分性能优化,但我们应该避免在过渡期间执行复杂计算。

浏览器兼容性

目前 View Transition API 在 Chrome 111+ 和 Edge 111+ 中得到支持。对于其他浏览器,建议提供渐进增强方案。

总结

View Transition API 极大地简化了复杂页面过渡动画的实现。通过简单的几行代码,我们就能为日夜模式切换添加专业级的动画效果。随着浏览器支持度的提升,这项技术必将成为 Web 动画的标准方案。