Javascript / jQuery - 动画背景改变与淡入淡出(无限)

时间:2015-11-08 22:14:59

标签: javascript jquery

我想每3秒更改一次div的背景。这需要循环,所以一旦最后一个背景图像显示它循环回到第一个,依此类推,依此类推。我很难这样做。

我在此之前发了一篇非常模糊且没有得到帮助的帖子。

    function animate() {  
    change1();
    change2();
    change3();
}
function change1() {  
       window.setInterval(function(){
        $('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg)');$('.content').css('transition','background 1s linear');
    },3000);
    }
    function change2() {  
       window.setInterval(function(){
        $('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg)');$('.content').css('transition','background 1s linear');
    },3000);
    }
    function change3() {  
       window.setInterval(function(){
        $('.content').css('background-image','url(x)');$('.content').css('transition','background 1s linear');
    },3000);
    }
    animate();

1 个答案:

答案 0 :(得分:1)

你完全过分复杂了这项任务。只需创建一个包含URL的数组和一个将设置幻灯片URL的函数,播放转换并设置一个标记下一个幻灯片索引的变量。然后使用setInterval()调用此函数。



var currentIndex = 0;
var urls = [
    'http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg',
    'http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg',
    'http://media.caranddriver.com/images/media/51/dissected-lotus-based-infiniti-emerg-e-sports-car-concept-top-image-photo-451994-s-original.jpg'
];
var length = urls.length - 1;

function slide() {
    $('.content').css('background-image', 'url(' + urls[currentIndex] + ')');
    $('.content').css('transition', 'background 1s linear');
    currentIndex = (currentIndex < length) ? currentIndex + 1 : 0;
}

slide();

window.setInterval(slide, 3000);
&#13;
.content {
    height: 200px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"></div>
&#13;
&#13;
&#13;