我有一个缩略图DOM元素,它需要转换为单击缩略图时打开的模态DOM元素。thumbnail和modal不是同一个DOM元素。为此,我想使用View Transitions API。
关于使用与DOM元素不同的过渡元素的主题,在Chrome文章“使用View Transitions API实现平滑和简单的过渡”的其中一章中有所介绍。
当尝试构建缩略图到模态转换时,我惊讶地发现transition元素的行为与我预期的不同。我做错了什么?
我已经编写了一个简单的代码变体,我希望在this codepen中工作。
<!-- HTML -->
<div id="thumbnail">Click me</div>
<div id="modal">You have opened the modal<div id="closer">X</div></div>
<div id="comment">
pink outline = ::view-transition-old<br> green outline = ::view-transition-new"
</div>
/* CSS */
#thumbnail {
position: relative;
border: 2px solid darkred;
display: inline-block;
padding: 40px;
cursor: pointer;
}
#thumbnail:hover {
background-color: #74747444;
}
#modal {
display: none;
position: absolute;
translate: -50% -50%;
top: 50%;
left: 50%;
padding: 80px;
border: 2px solid blue;
}
#closer {
position: absolute;
top: 4px;
right: 4px;
cursor: pointer;
}
::view-transition-old(modal),
::view-transition-new(modal) {
animation-duration: 5s;
}
::view-transition-old(modal) {
outline: 4px solid pink;
}
::view-transition-new(modal) {
outline: 4px solid green;
outline-offset: 4px;
}
// JavaScript
const thumbnail = document.querySelector("#thumbnail")
const modal = document.querySelector("#modal")
const closer = document.querySelector("#closer")
thumbnail.addEventListener("click", () => openModal())
closer.addEventListener("click", () => {
modal.style.display = "none"
})
function openModal() {
// Fallback for non-supporting browsers
if (!document.startViewTransition) {
modal.style.display = "block"
return
}
thumbnail.style.viewTransitionName = "modal"
modal.style.viewTransitionName = ""
const transition = document.startViewTransition(() => {
modal.style.display = "block"
})
transition.updateCallbackDone.then(() => {
thumbnail.style.viewTransitionName = ""
modal.style.viewTransitionName = "modal"
})
transition.finished.finally(() => {
modal.style.viewTransitionName = ""
})
}
1条答案
按热度按时间5n0oy7gb1#
将代码
thumbnail.style.viewTransitionName = null; modal.style.viewTransitionName = "modal"
从updateCallbackDone
promise回调移动到startViewTransition
回调就成功了。因此新代码如下所示(另见this codepen)。