jQuery 使用jquery每10秒更改具有淡入淡出效果的div的背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5507518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change background-image of a div with fade effect every 10 seconds with jquery
提问by Gogogo
I would like to create a slideshow in the header area of my page. It should change the background image every 10 seconds with a nice fade effect. And since I'm using jQuery for other stuff already I would like to use it for that as well.
我想在页面的标题区域创建幻灯片。它应该每 10 秒更改一次背景图像,并具有很好的淡入淡出效果。因为我已经将 jQuery 用于其他东西,所以我也想用它来做。
So my markup is just:
所以我的标记只是:
<div id="header">
<!--other stuff here...-->
</div>
And my CSS at the moment is:
我目前的 CSS 是:
#header {
background: url('images/header_slides/slide_1.jpg') no-repeat;
}
So now what I want is that after 10 seconds it would change to
所以现在我想要的是 10 秒后它会变成
#header {
background: url('images/header_slides/slide_2.jpg') no-repeat;
}
with a nice slow fade effect.
具有不错的缓慢淡入淡出效果。
回答by Hussein
I answered a similar question at How to fill browser window with rotating background Image?. You can fade background colors but not background images. You must have your images in <img>
tags and hide them by default display:none;
. Give your images position:absolute
and z-index:-1
so your images acts like a background images and are behind everything else.
我在如何用旋转背景图像填充浏览器窗口中回答了类似的问题?. 您可以淡化背景颜色,但不能淡化背景图像。您必须将图像放在<img>
标签中并默认隐藏它们display:none;
。提供您的图像position:absolute
,z-index:-1
因此您的图像就像背景图像一样,并且位于其他一切之后。
function test() {
$("img").each(function(index) {
$(this).hide();
$(this).delay(10000 * index).fadeIn(10000).fadeOut();
});
}
test();
Check working example at http://jsfiddle.net/ewsQ7/5/
在http://jsfiddle.net/ewsQ7/5/检查工作示例
回答by Robert Waddell
You can fade a background image with CSS3 using transitions.
您可以使用 CSS3 使用过渡来淡化背景图像。
Check it out at https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
在https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions查看
For your use, set up jQuery to change the background image, but apply the transition style using CSS. Anytime the background changes, it will transition according to the CSS3 style.
供您使用,设置 jQuery 以更改背景图像,但使用 CSS 应用过渡样式。每当背景发生变化时,它都会根据 CSS3 样式进行过渡。
#header
{
background: url('images/header_slides/slide_1.jpg') no-repeat;
transition: background 0.5s linear;
-moz-transition: background 0.5s linear; /* Firefox 4 */
-webkit-transition: background 0.5s linear; /* Safari and Chrome */
-o-transition: background 0.5s linear; /* Opera */
}
回答by Thomas Menga
You can't fade a background image. But you can fade a layer above your #header with your next background image...
你不能淡化背景图像。但是您可以使用下一个背景图像淡入 #header 上方的图层...