我是jQuery的新手。我有一些div,我想在无限循环中逐渐淡入1。为了淡出我在课堂active
上使用CSS动画;这是我尝试过的,但这只能工作一次。
HTML
<div id="bgContainer">
<div class="slides"> <img src=".." /> </div>
<div class="slides"> <img src=".." /> </div>
<div class="slides"> <img src=".." /> </div>
<div class="slides"> <img src=".." /> </div>
</div>
的jQuery
$('#bgContainer div').each(function(i) {
var currentSlide = $(this);
currentSlide.removeClass('active');
i = i + 1;
var intervel = i * 1000;
setTimeout(function () { SliderBG(currentSlide); }, intervel);
});
function SliderBG(currentSlide) {
currentSlide.addClass('active');
}
答案 0 :(得分:1)
这可能就是你想要的,它将循环遍历每个元素并添加.active
类,当它到达结尾时它将重新开始。
$(document).ready(function() {
Timer();
});
function Timer(){
var slides = $('#bgContainer .slides'),
counter = 0,
timer = setInterval(function() {
SliderBG(slides[counter]);
counter++
if (counter === slides.length) {
clearInterval(timer);
Timer()
}
}, 1000);
}
function SliderBG(currentSlide) {
$('#bgContainer .slides.active').add(currentSlide).toggleClass('active');
}
&#13;
.slides {
display: none;
}
.slides.active {
display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bgContainer">
<div class="slides"> <img src=".." alt="1"/> </div>
<div class="slides"> <img src=".." alt="2"/> </div>
<div class="slides"> <img src=".." alt="3"/> </div>
<div class="slides"> <img src=".." alt="4"/> </div>
</div>
&#13;
答案 1 :(得分:1)
(function(){
//get all the slides
var $slides = $('#bgContainer div');
//initialize the index to the first slide
var index = 0;
//start the loop
setTimeout(sliderBG, 1000);
function sliderBG () {
//remove active from all the elements
$slides.removeClass('active');
//put it on the next index
$slides.eq(index).addClass('active');
//increment the index, reset to 0 at the end
index = ++index % $slides.length;
//continue loop after a second
setTimeout(sliderBG, 1000);
}
}());
.slides {
background-color: #888;
}
.slides.active {
background-color: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bgContainer">
<div class="slides">Slide 1</div>
<div class="slides">Slide 2</div>
<div class="slides">Slide 3</div>
<div class="slides">Slide 4</div>
</div>