Window:pageswap 事件
當你在文件之間導航且上一個文件即將解除安裝時,會觸發 pageswap 事件。
這對於跨文件(MPA)檢視過渡很有用,可以從導航的出站頁面操作活動的過渡。例如,你可能希望跳過過渡,或者透過 JavaScript 自定義出站過渡動畫。
它還提供了對導航型別以及當前和目標文件歷史條目的訪問。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("pageswap", (event) => { })
onpageswap = (event) => { }
事件型別
一個 PageSwapEvent。繼承自 Event。
事件屬性
PageSwapEvent.activation只讀-
返回一個
NavigationActivation物件,其中包含同源導航的導航型別以及當前和目標文件歷史條目。如果導航在重定向鏈中的任何位置包含跨域 URL,則返回null。 PageSwapEvent.viewTransition只讀-
如果事件觸發時有活動的入站跨文件檢視過渡,則返回表示該過渡的
ViewTransition物件。如果不是這種情況,則返回null。
示例
js
window.addEventListener("pageswap", async (e) => {
// Only run this if an active view transition exists
if (e.viewTransition) {
const currentUrl = e.activation.from?.url
? new URL(e.activation.from.url)
: null;
const targetUrl = new URL(e.activation.entry.url);
// Going from profile page to homepage
// ~> The big img and title are the ones!
if (isProfilePage(currentUrl) && isHomePage(targetUrl)) {
// Set view-transition-name values on the elements to animate
document.querySelector(`#detail main h1`).style.viewTransitionName =
"name";
document.querySelector(`#detail main img`).style.viewTransitionName =
"avatar";
// Remove view-transition-names after snapshots have been taken
// Stops naming conflicts resulting from the page state persisting in BFCache
await e.viewTransition.finished;
document.querySelector(`#detail main h1`).style.viewTransitionName =
"none";
document.querySelector(`#detail main img`).style.viewTransitionName =
"none";
}
// Going to profile page
// ~> The clicked items are the ones!
if (isProfilePage(targetUrl)) {
const profile = extractProfileNameFromUrl(targetUrl);
// Set view-transition-name values on the elements to animate
document.querySelector(`#${profile} span`).style.viewTransitionName =
"name";
document.querySelector(`#${profile} img`).style.viewTransitionName =
"avatar";
// Remove view-transition-names after snapshots have been taken
// Stops naming conflicts resulting from the page state persisting in BFCache
await e.viewTransition.finished;
document.querySelector(`#${profile} span`).style.viewTransitionName =
"none";
document.querySelector(`#${profile} img`).style.viewTransitionName =
"none";
}
}
});
注意:請參閱Chrome DevRel 團隊成員列表以獲取此程式碼所引用的即時演示。
規範
| 規範 |
|---|
| HTML # 事件 - pageswap |
瀏覽器相容性
載入中…