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

浏览器兼容性

另见