跨文件檢視畫面轉換功能可讓您在多頁應用程式 (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
}