您还必须定义它如何淡化它,您可以使用opacity 来实现此效果,然后使用transition 参数定义动画属性,例如持续时间和缓动。
CSS:
#section0{
opacity: 0;
transition: opacity 2s; /* Define the duration of the opacity animation */
background-image: url("images/top_back2.jpg");
}
JavaScript(在您的 setTimeout 中):
$("#section0").css({
"opacity" : 1,
"background-image": "url(images/top_back.jpg)"
});
这是 JSFiddle 上的演示代码
https://jsfiddle.net/wtbmdaxc/
享受:)
更新:
为避免文本被覆盖,有两种方法可以做到这一点,要么您 separate your background image into another DIV 并将不透明度应用于该新 DIV,要么您 create a pseudo-element。之前已经在 SO 上回答了这两个问题。
让我们尝试第一种方法,它在你的情况下如何工作
HTML:
<div id="section0">
Example test. Lorem ipsum dolor sit amet.
<div id="bg-opacity"></div>
</div>
CSS:
#section0{
}
#section0 #bg-opacity{
position: absolute; /* Force this layer to appear at the top left of the div */
top: 0;
left: 0;
z-index: -1; /* Makes the image appear in the back and not covering the texts */
opacity: 0;
transition: opacity 2s; /* Define the duration of the opacity animation */
height: 500px;
width: 500px;
background-image: url("https://media.giphy.com/media/tIeCLkB8geYtW/giphy.gif");
}
JavaScript:
setTimeout(function(){
$("#bg-opacity").css({
"opacity" : 1,
"background-image": "url(https://media.giphy.com/media/tIeCLkB8geYtW/giphy.gif)"
});
}, 300);
还有一个关于 JSFiddle 的新演示:https://jsfiddle.net/zr7Lf0m5/