2012-01-27 127 views
0

這是我的代碼:的setTimeout不加延遲

function transition(index){ 
    $("#right-panel").find("img").each(function(){ 
     if ($(this).index() === index){ 
      setTimeout(function(){ 
       $(this).fadeIn(750); 
      }, 100000000); 
     }else{ 
      $(this).fadeOut(750); 
     } 
    }); 
} 

出於某種原因,在功能上的setTimeout不會導致對淡入延遲。我究竟做錯了什麼?

+0

我寧可懷疑fadeIn沒有發生 - 請確認嗎? – Alnitak 2012-01-27 22:17:35

+2

爲什麼延遲28小時?你嘗試過一個較小的(合理的)價值嗎? – 2012-01-27 22:17:49

+0

考慮緩存這些圖像(以便您不必每次都查詢)。 – 2012-01-27 22:18:58

回答

6

setTimeout回調this是不一樣的外面。

var self = this; 
setTimeout(function(){ 
    $(self).fadeIn(750); 
}, 100000000); 

雖然你可以只使用.delay()

$(this).delay(100000000).fadeIn(750) 

總體更好的方法似乎是使用.eq()搶要.fadeIn()之一,並.fadeOut()休息。

function transition(index){ 
    var images = $("#right-panel").find("img");// get all the images 
    var fadein = images.eq(index) 
         .delay(100000000) 
         .fadeIn(750); // fadeIn the one at "index" 
    images.not(fadein).fadeOut(750); // fadeOut all the others 
} 
+1

ooooooh現在我明白了 – 2012-01-27 22:22:01

0

爲什麼你需要setTimeout?

function transition(index){ 
    $("#right-panel").find("img").each(function(){ 
     if ($(this).index() === index){ // did you check this statement? 
      $(this).delay(100000000).fadeIn(750); 
     }else{ 
      $(this).fadeOut(750); 
     } 
    }); 
} 
+0

謝謝,這是訣竅:) – 2012-01-27 22:20:26

+0

只是一個音符 - 延遲使用setTimeout ..使用延遲的一個好處是不要擔心這個參考。 – 2012-01-27 22:25:03

+0

@SKS我的意思是專門爲他的例子。 – Cheery 2012-01-27 22:26:16