淡入新背景图片 Jquery

我有一个定义了背景图像的 div:


#section0{

        background-image: url("images/top_back2.jpg");

    }

我有一个 setTimeout 函数在 3 秒后将背景图像更改为其他内容


    $("#section0").css("background-image", "url(images/top_back.jpg)");

        }, 3000);

这工作正常,但无论我尝试什么,我似乎都无法使该图像淡入淡出。


任何想法将不胜感激,它只是像这样出现在屏幕上,而且非常刺耳。我无法向整个元素添加 CSS3 淡入,因为前 3 秒内没有显示里面的内容,我需要它出现。


潇湘沐
浏览 149回答 1
1回答

慕丝7291255

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

相关分类

JavaScript