Astro View Transitions:无缝页面切换动画

#astro#动画#view-transitions
Astro View Transitions:无缝页面切换动画

什么是 View Transitions

Astro 的 <ClientRouter /> 组件基于浏览器的 View Transitions API, 在页面切换时自动添加淡入淡出动画,不需要手动管理路由。

BaseLayout.astro<head> 中引入即可:

import { ClientRouter } from 'astro:transitions';

<head>
  <ClientRouter />
</head>

生命周期事件

View Transitions 切换页面时会触发一系列事件,用来管理第三方库的初始化和销毁:

事件 触发时机 典型用途
astro:before-preparation 开始准备新页面 显示加载指示
astro:after-preparation 新页面 DOM 就绪 预处理内容
astro:before-swap 旧页面即将被替换 销毁旧实例
astro:page-load 新页面已挂载 初始化新实例

与 GSAP / Lenis 配合

平滑滚动和滚动动画需要在页面切换时正确销毁和重建:

document.addEventListener('astro:page-load', () => {
  initSmoothScroll();
  initPageAnimations();
});

document.addEventListener('astro:before-swap', () => {
  destroySmoothScroll();
  destroyPageAnimations();
});

如果不销毁旧的 Lenis 实例,多个实例会同时驱动滚动,导致页面抖动。

自定义动画

通过 transition:animate 指令可以覆盖默认动画:

<article transition:animate={{ name: 'fade', duration: '0.3s' }}>
  ...
</article>

也可以用 transition:persist 让某个元素在页面切换时保持不变(比如音频播放器)。

兼容性

不支持 View Transitions API 的浏览器会自动降级为普通跳转,不影响功能。