借助跨文档视图过渡,您可以在多页应用 (MPA) 的不同页面之间创建流畅、类似应用的过渡效果。默认情况下,浏览器会执行淡入淡出效果,但您可以自定义此效果,使其与网站的美学风格相匹配。
实施步骤
1. 选择启用跨文档视图过渡
来源网页和目标网页都必须选择启用视图过渡,浏览器才能在导航时触发视图过渡。
/* Respect user's preference for reduced motion */
@media (prefers-reduced-motion: no-preference) {
/* Add to a global stylesheet shared by both pages */
@view-transition {
/* Enables transitions for same-origin navigations */
navigation: auto;
}
}
2. 自定义过渡动画(可选)
您可以使用伪元素定位过渡的新旧状态,以创建滑动或揭示等效果。
/* Customizing the outgoing page animation */
::view-transition-old(root) {
/* Move the old page out to the left */
animation: 0.4s ease-in both slide-out;
}
/* Customizing the incoming page animation */
::view-transition-new(root) {
/* Move the new page in from the right */
animation: 0.4s ease-out both slide-in;
}
@keyframes slide-out {
to { transform: translateX(-20%); opacity: 0; }
}
@keyframes slide-in {
from { transform: translateX(100%); }
}
3. 创建方向性过渡(可选)
您可能需要根据要浏览的页面使用不同的过渡效果。例如,从首页导航到联系信息页面时,您可能希望新内容从右侧进入。当用户返回首页时,不应再显示相同的效果。
如果无论您如何访问某个网页,该网页始终具有相同的过渡类型,您可以在 @view-transition 规则中使用 types 指定该类型。
@media (prefers-reduced-motion: no-preference) {
@view-transition {
navigation: auto;
/* Specify the types of view transitions that will always be used on this page. */
types: previous;
}
}
您还可以在 pagereveal 的事件监听器中有条件地指定转换类型。
window.addEventListener("pagereveal", async (e) => {
if (e.viewTransition && window.navigation?.activation) {
// Use application-specific logic to compute a transition type
const transitionType = yourTransitionTypeLogic(navigation.activation.from, navigation.activation.entry);
e.viewTransition.types.add(transitionType);
}
});
然后,使用 :active-view-transition-type() 伪选择器为每种类型应用不同的动画。
:active-view-transition-type(next) {
&::view-transition-old(root) {
animation-name: slide-out-next;
}
&::view-transition-new(root) {
animation-name: slide-in-next;
}
}
:active-view-transition-type(previous) {
&::view-transition-old(root) {
animation-name: slide-out-previous;
}
&::view-transition-new(root) {
animation-name: slide-in-previous;
}
}
后备策略
如果浏览器不支持视图过渡或跨文档视图过渡,则会执行标准的即时网页导航。跨文档视图过渡是一种渐进增强功能,网站的核心功能不受影响。
如需在 JavaScript 中检查支持情况,请执行以下操作:
if ('onpagereveal' in window) {
// Browser supports cross-document view transitions
}
如果浏览器不支持 Navigation API,您将无法使用该 API 来确定过渡类型。请使用其他方法来确定转换类型,或提供后备转换类型。否则,浏览器将执行标准的即时网页导航。
如需在 JavaScript 中检查支持情况,请执行以下操作:
if (window.navigation?.activation) {
// Browser supports the Navigation API
}