Window:pagereveal 事件

可用性有限

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

當文件首次呈現時,會觸發 pagereveal 事件,這可能是在從網路載入新文件時,或在啟用文件時(無論是從回退/前進快取 (bfcache) 還是預渲染)。

這在跨文件 (MPA) 檢視過渡中很有用,用於從導航的入站頁面操縱活動過渡。例如,你可能希望跳過過渡,或透過 JavaScript 自定義入站過渡動畫。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("pagereveal", (event) => { })

onpagereveal = (event) => { }

事件型別

一個 PageRevealEvent。繼承自 Event

Event PageRevealEvent

事件屬性

PageRevealEvent.viewTransition 只讀

如果事件觸發時有活動的入站跨文件檢視過渡,則返回表示該過渡的 ViewTransition 物件。如果不是這種情況,則返回 null

示例

js
window.addEventListener("pagereveal", async (e) => {
  // If the "from" history entry does not exist, return
  if (!navigation.activation.from) return;

  // Only run this if an active view transition exists
  if (e.viewTransition) {
    const fromUrl = new URL(navigation.activation.from.url);
    const currentUrl = new URL(navigation.activation.entry.url);

    // Went from profile page to homepage
    // ~> Set VT names on the relevant list item
    if (isProfilePage(fromUrl) && isHomePage(currentUrl)) {
      const profile = extractProfileNameFromUrl(fromUrl);

      // 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 names after snapshots have been taken
      // so that we're ready for the next navigation
      await e.viewTransition.ready;
      document.querySelector(`#${profile} span`).style.viewTransitionName =
        "none";
      document.querySelector(`#${profile} img`).style.viewTransitionName =
        "none";
    }

    // Went to profile page
    // ~> Set VT names on the main title and image
    if (isProfilePage(currentUrl)) {
      // 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 names after snapshots have been taken
      // so that we're ready for the next navigation
      await e.viewTransition.ready;
      document.querySelector(`#detail main h1`).style.viewTransitionName =
        "none";
      document.querySelector(`#detail main img`).style.viewTransitionName =
        "none";
    }
  }
});

注意:請參閱Chrome DevRel 團隊成員列表以獲取此程式碼所引用的即時演示。

規範

規範
HTML
# event-pagereveal

瀏覽器相容性

另見