2012-07-19 116 views
0

我的大腦它會爆炸..爲什麼這個不工作?我嘗試用時間間隔動畫幾個div的,並試圖寫更少的代碼,但是這不工作JQuery setTimeOut while循環

var cargaCont = function(){ 
     o = 1; 
     var animacion = function(i){ 
      $('#page2txt'+i).animate({ 
       height:'20' 
      },200,function(){ 
       $('#page2img'+i).animate({ 
        left:'0', 
        right:'0' 
       },200,function(){ 
        i++; 
        return i; 
       }); 
      }); 
     } 
     while(o < 3){ 
      setTimeout(function(){o = animacion(o);},200); 
     } 
    } 
+0

你可以發佈標記嗎?並解釋什麼是所需的效果?這段代碼中有許多不必要的行。 – undefined 2012-07-19 07:21:44

回答

1

這段代碼的問題:

while(o < 3){ 
    setTimeout(function(){o = animacion(o);},200); 
} 

是由時間setTimeout延遲功能執行,o已經是3,因此,以animacion 3趟,而不是1和2

所有呼叫爲了解決這個問題,您應該通過使用立即直接「本地化」的o值te功能。

while(o < 3){ 
    //o out here is from cargaCont 
    (function(o){ 
     //override o by naming the passed variable o 
     setTimeout(function(){ 
      o = animacion(o); //now o refers to the local o 
     },200); 
    }(o)); //execute inner function, passing in o 
} 

這使得在setTimeout使用的功能的o綁定到本地函數的o而不是cargaCont函數的o

0

我不是100%肯定你會什麼的,但我要猜你基本上要遍歷一些動畫,也許是這樣的:

var cargaCont = function(){ 
    var i = 1, 
     animacion = function(i){ 
      $('#page2txt'+i).animate({ 
       height:'20' 
      },200,function(){ 
       $('#page2img'+i).animate({ 
        left:'0', 
        right:'0' 
       },200,function(){ 
        if(i < 3){ 
         animacion(++i); 
        } 
       }); 
      }); 
     }; 
    animacion(i); 
}; 

編輯爲你覺得合適或張貼一些標記來進一步解釋。

乾杯。