Window:pagereveal 事件
当文档首次呈现时,会触发 pagereveal 事件,这可能是在从网络加载新文档时,或在激活文档时(无论是从回退/前进缓存 (bfcache) 还是预渲染)。
这在跨文档 (MPA) 视图过渡中很有用,用于从导航的入站页面操纵活动过渡。例如,你可能希望跳过过渡,或通过 JavaScript 自定义入站过渡动画。
语法
在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("pagereveal", (event) => { })
onpagereveal = (event) => { }
事件类型
一个 PageRevealEvent。继承自 Event。
事件属性
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 |
浏览器兼容性
加载中…