2014-09-28 38 views
1

现在我想用淡入效果来改变身体的背景。 如何用淡入效果改变身体的背景效果

var imgSrcs = ["img/bg1.jpg","img/bg2.jpg","img/bg3.jpg","img/bg4.jpg","img/bg5.jpg"]; 
 
setInterval(function() { 
 
    $("body").css("background-image", "url(" + imgSrcs[imgSrcs.push(imgSrcs.shift()) - 1] + ")"); 
 
}, 3000);
有这个代码,它工作正常,但我想添加淡入淡出效果,而它改变。

+0

jQuery的链接阅读起来。 http://www.w3schools.com/jquery/jquery_chaining.asp。您可以将多个方法链接在一起。所以你需要添加的是.fadeIn()方法到你的$(“body”)链的末尾。 – 2014-09-29 00:18:56

+0

@TylerEvans我试过了,但它不工作,因为它淡出了身体的全部内容..我想改变背景不是整个页面 – user2976078 2014-09-29 00:24:09

+0

是的,这是一个很好的观点。无论如何,它们看起来都是一个很好的答案。 – 2014-09-29 00:27:50

回答

1

您可以在一个绝对定位的模拟背景使用fadeIn()和​​

var imgSrcs =[ 
 
    "http://placehold.it/700x200/&text=bg2.jpg", 
 
    "http://placehold.it/700x200/&text=bg3.jpg", 
 
    "http://placehold.it/700x200/&text=bg4.jpg", 
 
    "http://placehold.it/700x200/&text=bg5.jpg", 
 
    "http://placehold.it/700x200/&text=bg1.jpg" 
 
]; 
 

 
$('.background').fadeIn(1000, animateBackground()); 
 

 
function animateBackground() { 
 
    
 
    window.setTimeout(function(){ 
 
     
 
     var url = imgSrcs[imgSrcs.push(imgSrcs.shift()) - 1]; 
 
     
 
     $('.background').delay(1000).fadeOut(1000, function(){ 
 
       
 
      $(this).css("background-image", "url(" + url + ")") 
 
       
 
     }).fadeIn(1000, animateBackground()) 
 

 
    }); 
 
}
.background { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
    background-repeat: no-repeat; 
 
    z-index: -9999; 
 
    display: none; 
 
    background-image: url('http://placehold.it/700x200/&text=bg1.jpg'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="background"></div> 
 

 
<h1>Hello World</h1>

或者,您可以使用CSS3过渡

var imgSrcs =[ 
 
    "http://placehold.it/700x200/&text=bg1.jpg", 
 
    "http://placehold.it/700x200/&text=bg2.jpg", 
 
    "http://placehold.it/700x200/&text=bg3.jpg", 
 
    "http://placehold.it/700x200/&text=bg4.jpg", 
 
    "http://placehold.it/700x200/&text=bg5.jpg" 
 
]; 
 

 
setInterval(function() { 
 
    $("body").css("background-image", "url(" + imgSrcs[imgSrcs.push(imgSrcs.shift()) - 1] + ")"); 
 
}, 1000);
body { 
 
    -webkit-transition: background-image 0.5s ease-in-out; 
 
    -moz-transition: background-image 0.5s ease-in-out; 
 
    -ms-transition: background-image 0.5s ease-in-out; 
 
    -o-transition: background-image 0.5s ease-in-out; 
 
    transition: background-image 0.5s ease-in-out; 
 
    background-repeat: no-repeat; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

谢谢:)它工作正常,但看起来像背景的宽度和高度滑动..我们可以做它淡入淡出,然后淡出 – user2976078 2014-09-29 00:32:22

+0

你忘了我:) – user2976078 2014-09-29 01:23:56

+0

用fadeIn fadeOut选项更新。 – 2014-09-29 05:04:07