javascript - FadeIn 新的背景图像 Jquery
问题描述
我有一个定义了背景图像的 div:
#section0{
background-image: url("images/top_back2.jpg");
}
我有一个 setTimeout 函数在 3 秒后将背景图像更改为其他内容
$("#section0").css("background-image", "url(images/top_back.jpg)");
}, 3000);
这工作正常,但无论我尝试什么,我似乎都无法让这个图像淡入。
任何想法都将不胜感激,它只是像这样出现在屏幕上,而且非常刺耳。我无法将 CSS3 淡入添加到整个元素中,因为前 3 秒内没有显示内部内容,我需要它出现。
谢谢!
解决方案
您还必须定义它如何淡化它,您可以使用它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)"
});
Here is a demo on JSFiddle with the code https://jsfiddle.net/wtbmdaxc/
Enjoy :)
Update:
To avoid the text to being covered, there are two ways to do it, either you separate your background image into another DIV and apply the opacity to that new DIV or you create a pseudo-element. Both of which have already been answered on SO before.
Let's try the first method, how it will work in your case
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);
And a new demo on JSFiddle: https://jsfiddle.net/zr7Lf0m5/
推荐阅读
- php - 如何在 laravel 5.6 中删除特定属性并返回主页
- python - 代码删除了停用词,但 Word2vec 仍然为停用词创建 wordvector?
- salesforce - 在 Workbench 中获取查询结果,而不是在顶点类/脚本中
- vue.js - 如何在 Laravel Nova 中扩展一个字段?
- php - 在 Symfony 3.4 中使用 knp-menu-bundle 时出现问题
- php - 如何访问数组(json)中对象的位置并通过php更改其值
- excel - 仅将最后一行数据从 Excel 复制到 Word
- c - 为什么 Makefile 不生成对象?
- sql - Postgres WITH 查询和多个后续语句
- c++ - 具有布尔逻辑的单个返回是否等同于保护子句?