PageSwapEvent

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

PageSwapEvent 事件物件可在 pageswap 事件的處理函式中使用。

當您導航到其他文件時,在前一個文件即將解除安裝時會觸發 pageswap 事件。在跨文件導航期間,PageSwapEvent 事件物件允許您從正在導航離開的文件中操縱相關的 檢視過渡(透過訪問相關的 ViewTransition 物件),前提是導航觸發了檢視過渡。它還提供導航型別以及當前和目標文件的資訊。

建構函式

PageSwapEvent()

建立一個新的 PageSwapEvent 物件例項。

例項屬性

activation 只讀

包含一個 NavigationActivation 物件,其中包含同源導航的導航型別以及當前和目標文件的歷史條目。如果導航的重定向鏈中任何位置存在跨源 URL,則返回 null

viewTransition 只讀

包含一個 ViewTransition 物件,代表跨文件導航的活動檢視過渡。

示例

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
# the-pageswapevent-interface

瀏覽器相容性

另見