2016-04-30 12 views
1

2秒ごとに切り替える画像のスライドショーを作成したいのですが、このコードがあります。JQueryスライドショーを1回だけ繰り返しますか?

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

ニース。 StackOverflowで常に新しいことを学ぶ! –

関連する問題