2012-09-19 44 views
0

我試圖做一個圖像推子畫廊,循環通過一些圖像,然後重複。我已經成功地寫出了它通過圖像淡化的部分,但我無法弄清楚如何重複它。我使用的當前代碼只是無限加載,我認爲是因爲我創建了一個無限循環,但我不知道如何或如何繞過它。自定義圖像推子

jQuery的

//create array with the images id tags 
var img_arr = [ 
      '#img1', 
      '#img2', 
      '#img3' 
     ] 
     var i = 0; 
     arr_length = img_arr.length; 
     gal_repeat = img_arr.length - 1; 
     $(document).ready(function img_gallery() { 
      //loop through the fade animation until the end of the array 
      for (i = 0; i < arr_length; i++) { 
       $(img_arr[i]) 
        .animate(
         { opacity: '1.0' }, 2000 
        ); 
       $('.img').delay(1000).animate({opacity: 0.0}, 2000); 
       //THIS IS WHERE THE PROBLEM IS. if I comment out this 'if' 
       //statement, the gallery works fine but doesn't repeat 
       if (i == gal_repeat) { 
        i = 0; 
       } 
      } 
     }) 
+0

無限循環是因爲你的for循環設定i的值回0內,和if語句會總是在循環的最後一次運行中被擊中,因此無限循環。我會建議尋求一種不同的方法來建立圖像的結尾,除了循環計數器變量 – OJay

+0

我知道它會創建一個無限循環,但不應該循環回到開始部分,直到所有圖像都被淡化延時?我想我的問題是試圖理解爲什麼它導致頁面崩潰 – Hat

+0

你循環沒有直到!?,在循環中沒有任何地方停止,基於i的一個原則,你保持重置爲零隻要我到最後一次迭代。你需要重新思考你的邏輯。 – OJay

回答

0

您可以使用setInterval的重複性的東西:

//create array with the images id tags 
var images = ['#img1', '#img2', '#img3']; 
numberOfImages = images.length; 

$(document).ready(function() { 

    var num = 0; 
    setInterval(function() { 
     num = (num + 1) % numberOfImages; 

     $(images[num]).animate({ 
      opacity: '1.0' 
     }, 2000); 

     $('.img').delay(1000).animate({ 
      opacity: 0.0 
     }, 2000); 

    }, 5000); 
});