如何用淡入效果改变身体的背景

时间:2014-09-28 23:59:42

标签: jquery

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



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);



  有这个代码,它工作正常,但我想在它改变时添加淡入效果。

1 个答案:

答案 0 :(得分:1)

您可以在绝对定位的模拟背景上使用fadeIn()fadeOut()

& #13;

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>
&#13;
&#13;
&#13;

或者,你可以使用CSS3过渡

&#13;
&#13;
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);
&#13;
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;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;