2015-04-04 91 views
1

我想添加圖像添加到元素之間的一段時間。這是我的代碼:將圖像延遲添加到div for for循環

<script> 
     var aantalkeergeklikt = 0; 
     var uniekeid = 0; 
     var pictures = ["../Spel in jQuery/img/bubbles/bom.png", "../Spel in jQuery/img/bubbles/green.png", "../Spel in jQuery/img/bubbles/red.png", "../Spel in jQuery/img/bubbles/yellow.png", "../Spel in jQuery/img/bubbles/orange.png", "../Spel in jQuery/img/bubbles/purple.png", "../Spel in jQuery/img/bubbles/blue.png"]; 
     var size = pictures.length 

     for (i = 0; i < 20; i++) { 
      uniekeid = uniekeid + 1; 
      var x = Math.floor(size * Math.random()) 

      var item = $("<img src='" + pictures[x] + "' alt='" + uniekeid + "' />").hide().delay("slow").fadeIn(); 
      $('#depionnen').append(item); 
      console.log(item.alt); 
     } 

    </script> 

此時,在添加所有圖像後應用延遲。

有人可以幫助我嗎?

回答

0

你必須使用setTimeout來延遲for循環。

var i = 1;      // set your counter to 1 

function myLoop() {   // create a loop function 
    setTimeout(function() { // call a 3s setTimeout when the loop is called 
     alert('hello');   // your code here 
     i++;      // increment the counter 
     if (i < 10) {   // if the counter < 10, call the loop function 
     myLoop();    // .. again which will trigger another 
     }      // .. setTimeout() 
    }, 3000) 
} 

myLoop();      // start the loop 

Source

所以,在你的榜樣,將是這樣的:

var i = 1;      

function myLoop() {   
    setTimeout(function() {  
     uniekeid = uniekeid + 1; 
     var x = Math.floor(size * Math.random()) 
     var item = $("<img src='" + pictures[x] + "' alt='" + uniekeid + "' />").hide().delay("slow").fadeIn(); 
     $('#depionnen').append(item); 
     console.log(item.alt); 

     i++;      
     if (i < 20) {    
     myLoop();    
     }       
    }, 3000) 
} 

myLoop();      
+0

謝謝!它現在有效。 – 2015-04-04 13:18:21

+0

考慮接受別人知道的答案;) – Bram 2015-04-04 13:20:53

0

下面是這類問題的通用解決方案:

function nextPic() { 
    if(pictures.length) { 
    var item = $('<img src="' + pictures.shift() + '">') 
       .hide() 
       .delay('slow') 
       .fadeIn(nextPic); 

    $('#depionnen').append(item); 
    } 
} //nextPic 

nextPic(); 

Working Fiddle

+0

這不是他要求的。他要求延遲。不影響 – Bram 2015-04-04 13:21:30

+0

@BramDriesen,將**從slow延遲到fadeIn應該完成同樣的事情。如果這不符合他的要求,Op可以做出迴應。 – 2015-04-04 13:23:10

+0

不是。以此爲例。一個頁面加載一個for循環的10K圖片一次,但有效果!==加載延遲。它可能看起來一樣。但它有些不同。 – Bram 2015-04-04 13:25:44

0

jQuery.delay()只會延遲對同一元素的影響。 嘗試使用setTimeout()代替,這將是這個樣子:

for (i = 0; i < 20; i++) { 
    uniekeid = uniekeid + 1; 
    var x = Math.floor(size * Math.random()) 

    var item = $("<img src='" + pictures[x] + "' alt='" + uniekeid + "' />").hide(); 
    $('#depionnen').append(item); 

    setTimeout(function(item){ item.fadeIn(); }, i*600, item); 
} 

演示:http://jsfiddle.net/5eygxdv1/