使用 jQuery 时,身体背景图像会随着淡入淡出而改变吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9053500/
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
body background images change with fading using jQuery?
提问by Jitendra Vyas
I'm using banner images in background of body {background: url(banner1.jpg)}
我在身体背景中使用横幅图像 {background: url(banner1.jpg)}
I have multiple image like banner1.jpg, banner2.jpg, banner3.jpg.
我有多个图像,如banner1.jpg、banner2.jpg、banner3.jpg。
I want to change images automatically after specific interval like 5-10 seconds.
我想在 5-10 秒等特定时间间隔后自动更改图像。
How to do this with jQuery? I don't want to use inline images.
如何用 jQuery 做到这一点?我不想使用内联图像。
回答by ori
Just set the background-image
of the element:
只需设置background-image
元素的:
$(elem).css('background-image', 'url(banner2.jpg)');
EDITto fade in and out, you'll need to fade the container element:
编辑淡入淡出,您需要淡入淡出容器元素:
$(elem).fadeOut('fast', function() {
$(elem).css('background-image', 'url(banner2.jpg)')
.fadeIn('fast');
});
回答by xdazz
var images = ['banner1.jpg', 'banner2.jpg', 'banner3.jpg'];
var i = 0;
setInterval(function(){
$('body').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
}, 5000);
UPDATE:If you want to change image smoothly, I suggest put all banner images into one image, and set it as body's background image, then use .animatemethod with background-position to change the banner image.
更新:如果你想平滑地改变图像,我建议将所有横幅图像放在一张图像中,并将其设置为主体的背景图像,然后使用.animate方法和背景位置来更改横幅图像。
回答by jquery
I would like to say that this information is very useful and it works. I tried something different using JQuery:
我想说这些信息非常有用,而且很有效。我使用 JQuery 尝试了一些不同的东西:
HTML:
HTML:
<div id="pic"></div>
<div id="bat"></div>
CSS:
CSS:
#pic {
position: absolute;
z-index: -98;
top: 0;
left: 0;
background-image: url ('http://wallpaperfast.com/wp-content/uploads/2013/05/Calm-sea-breeze-notebook-background-images-Desktop-Wallpaper.jpg');
display: none;
}
#bat {
position: absolute;
z-index: -98;
top: 0;
left: 0;
background-image: url('http://www.designmyprofile.com/images/graphics/backgrounds/background0172.jpg');
display: none;
}
JS:
JS:
$('#pic').css({
height: $(window).height(),
width: $(window).width()
}).fadeIn('slow', function () {
$('#pic').css('background-image', 'url(http://wallpaperfast.com/wp-content/uploads/2013/05/Calm-sea-breeze-notebook-background-images-Desktop-Wallpaper.jpg)');
$('#pic').fadeOut('slow');
$('#pic').fadeIn('slow');
});