缓存图像的"transition: opacity 1"不起作用。如何替换 2 个"img"元素?



因此,我通过将一个<img>元素替换为另一个元素来进行平滑的背景更改。一切顺利,但是如果我替换到已经使用的图像,则过渡不起作用。

点击"背景2"。它取代了完美。
点击"背景3"。相同的结果。单击"背景
1"或"背景 2"。它崩溃了

在Codepen
上也有我的代码 还有原始页面,您可以在下面看到:

<html>
<head>
<title>Background change</title>
<meta charset="utf-8"/>
<style>
/* Nothing important */
#background { z-index: -100; }
.background {
width: 100vw;
height: 100vh;
object-fit: cover;
position: fixed;
transition: opacity 2s;
}
</style>
<script>
function setBackground(url) {
// --- Do not change if it is the same image
if (background.getAttribute("src") == url) return
// Create new background image elememt
let newBackground = document.createElement("img")
newBackground.id = "newBackground"
newBackground.className = "background"
// --- Place new img tag behind old img tag
newBackground.style.opacity = 0
newBackground.style.zIndex = -90
newBackground.src = url
// --- Insert img tag in DOM
background.after(newBackground)
// --- Start transition
function start(){ console.log("start"); newBackground.style.opacity = 1 }
// --- Runs after transition
function end(){
console.log("end")
// --- Remove old img from DOM
background.remove()
// --- Set standard values for 'id' and 'z-index'
newBackground.id = "background"
newBackground.style.zIndex = -100
// --- Assign 'background' to new img element (for future usage)
background = document.getElementById("background")
}
newBackground.addEventListener("transitionend", end)
// --- Start transition if img is cached
// --- Maybe here is an error?
if (newBackground.complete) start()
else newBackground.addEventListener("load", start)
}
document.addEventListener("DOMContentLoaded", function(){
background = document.getElementById("background")
})
</script>
</head>
<body>
<img id="background" class="background" src="https://i.imgur.com/6IjDFqg.jpg"/>
<button onclick="setBackground('https://i.imgur.com/6IjDFqg.jpg')">Background 1</button><br/>
<button onclick="setBackground('https://i.imgur.com/Ai5Zbq1.jpg')">Background 2</button><br/>
<button onclick="setBackground('https://i.imgur.com/9jHOYe9.jpg')">Background 3</button><br/>
</body>
</html>

如何在纯 JavaScript 中用过渡替换两个<img>标签?也许有一些更简单的方法。或者我只是做错了什么。

(对不起我的英语(

没有足够的时间完全研究它,但看起来在设置完整标志时不会触发 transitionend 事件,因此永远不会调用 end 函数来更改不透明度。

如果更改以下两行:

if (newBackground.complete) start()
else newBackground.addEventListener("load", start)

进入这个

newBackground.addEventListener("load", start)

然后它将始终如一地进行转换(前提是您等到

最新更新