不幸的是 CSS 不支持背景图像的动画(通过过渡)。为什么?事实上,我不确定为什么。但只要知道他们不这样做就足够了。 Javascript 通过扩展 CSS 功能直接工作。简而言之,如果不编写一段非常复杂的代码来破解其功能,就无法使用 Javascript 完成您想要做的事情。
然而,使用 jQuery 有一个简单的解决方法,这实际上也会使您的源代码变得不那么复杂。做身体relative
,将每个单独的背景图像添加到bottom您的源代码(使它们在其他所有内容之后加载)位于命名包装器内。让我们一起去#backgrounds
.
<style>
body{
height:100%;
position:relative
}
#backgrounds img{
position:absolute;
z-index:1; // this is important
top:0;
left:0;
width:100%;
height:100%;
opacity:0;
display:none;
}
#wrapper{
position:relative;
z-index:3; // again, this is important
}
</style>
我们将包装器的 z-index 设置为高于图像的 z-index,以便我们的内容位于它们的前面,从而给人一种图像是背景图像的错觉。改变position:absolute
to position:fixed
如果你想要一个background-attachment:fixed
影响。我假设您希望它们的宽度和高度是视口的宽度和高度;如果没有,请将它们更改为任何内容。我们将图像设置为display:none
阻止他们all页面加载时加载。哎呀!
<div id="wrapper">
all of your page are belong to us...
</div>
<div id="backgrounds">
<img src="background/one.jpg" alt="">
<img src="background/two.jpg" alt="">
<img src="background/three.jpg" alt="">
</div>
然后使用基于图像数量的计数器简单地循环浏览每个图像(这样您就可以轻松地在以后轻松剪切和粘贴更多图像):
$(function(){
var total = $('#backgrounds img').length;
var counter = 1;
function cycle(){
// Makes old backgrounds appear beneath new ones
$('#backgrounds img').css('z-index','1')
// Set it to display and opacity 0 so we get the effect
$('#backgrounds img:nth-child('+counter+')').css({'opacity':'0','display':'block','z-index':'2'})
// Fade the background in
$('#backgrounds img:nth-child('+counter+')').animate({'opacity':'1'},1500)
// increase the counter
counter++
// make sure we're working within the quantity of images we have
if( counter > total ){ counter = 1 }
}
cycle();
setInterval(function(){cycle()},6000);
})