2016-04-30 4 views
1

Так что я хочу сделать слайд-шоу с изображениями каждые две секунды, и у меня есть этот код.Запуск слайд-шоу JQuery только один раз?

HTML:

<div class="fadeIn"> 
    <img src="img/city.png" class="remimg" id="city"> 
    <img src="img/shop.png" class="remimg" id="shop"> 
    <img src="img/ice-cream-cone.png" class="remimg" id="icecream"> 
</div> 

JavaScript:

$(function(){ 
    $('.fadeIn img:gt(0)').hide(); 
    setInterval(function(){ 
     $('.fadeIn :first-child').fadeOut() 
      .next('img').fadeIn() 
      .end().appendTo('.fadeIn');}, 
     2000); 
}); 

Как мне сделать это только один раз повторять?

ответ

1

Вы можете установить счетчик, назначить интервал переменной и затем очистить интервал.

Here's a Working Fiddle

Измените JavaScript следующим образом:

$(function(){ 
    $('.fadeIn img:gt(0)').hide(); 
    // assign this to a variable, since we're going to check it often 
    var total = $('.fadeIn img').length; 
    // initialize the counter 
    // You can adjust this number as desired. 
    // For example, set it to 0 if you want the show to end on the first slide 
    var count = 1; 
    // assign the interval to a variable so we can clear it 
    var slideInterval = setInterval(function() { 
     // if the current slide count is equal to or greater than the total slides, clear the interval 
     if (++count >= total) { 
      // stops the slideInterval (and therefore the slideshow) 
      clearInterval(slideInterval); 
      // You could do other things here if desired.... 
     } 
     $('.fadeIn :first-child').fadeOut() 
      .next('img').fadeIn() 
      .end().appendTo('.fadeIn');}, 
     2000); 
}); 
2

Это, вероятно, проще использовать рекурсивную функцию без добавления изображения, а затем просто остановится, когда будет достигнуто последнее изображение

$(function() { 
    var all = $('.fadeIn img'), 
     first = all.first(), 
     last = all.last(); 

    all.not(first).hide(); 

    (function fn(image) { 
     setTimeout(function() { 
      var f = image.fadeOut().next().fadeIn(); 
      if (f.get(0) !== last.get(0) ) fn(f); 
     }, 2000); 
    }(first)); 
}); 

FIDDLE

+0

Nice. Всегда изучайте что-то новое в StackOverflow! –

Смежные вопросы