使用JS淡化多个div

时间:2017-04-01 10:25:00

标签: javascript jquery html css

我有两个或将来可能会有更多div与css中的背景图像。我想在一个循环中淡入淡出它们。

我正在尝试做这样的事情,但它不起作用。

$(window).load(function(){
var divs = $('.fade');


function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;
    
    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }
    
    var next = divs.eq(nextIndex);
    
    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });
    
    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
#one {
   background-image: url("Test_bg.jpg");
margin-top: -150px;
min-height: 100%;
background-attachment: fixed;
}

#two {
   background-image: url("Test_bg1.jpg");
margin-top: -150px;
min-height: 100%;
display: block;
background-attachment: fixed;
}
<div id="one" class="fade current">
</div>
	<div id="two" class="fade">
</div>

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

你最后在})处导致语法错误

&#13;
&#13;
$(window).load(function(){
var divs = $('.fade');


function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
})
&#13;
#one {
  color: red
}

#two {
  color: blue
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="fade current">a
</div>
<div id="two" class="fade">b
</div>
&#13;
&#13;
&#13;