2017-04-01 73 views
0

我有两个或未来可能会更多div与CSS中的背景图像。我想在循环中淡入淡出。与JS褪色多个div

我想要做这样的事情,但它不起作用。

$(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> 
 
\t <div id="two" class="fade"> 
 
</div>

感谢您的帮助

回答

0

你是在与原因语法错误

$(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 { 
 
    color: red 
 
} 
 

 
#two { 
 
    color: blue 
 
}
<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>

结束mising })