2016-01-28 91 views
-1

裏面動畫的方法我有下面的循環,從1數到100。Javascript的jQuery的 - for循環

我想用動畫的方法這個循環裏面通過改變其頂部平穩地移動畫面,即並留下屬性。

雖然我可以讓圖片移動,但它在一個生澀的動畫中。我可能有點愚蠢,但它似乎在一個命中而不是逐漸執行所有動畫。

這是否與JavaScript是異步?

也有一種方法,我可以得到的東西在JavaScript中重複,而不是設置一個循環有一種方法,功能可以調用自己在最後,所以,例如,我可以有一個動畫顯示不斷反彈的div等。現在我必須建立一個預定義的循環。

for (i=1; i < 100; i++) { 
    var FirstTop = (FirstTop + FirstTopGoal); 
    var FirstLeft= (FirstLeft+ (FirstLeftGoal)); 
    var SecondTop = (SecondTop+ (SecondTopGoal)); 
    var SecondLeft = (SecondLeft + (SecondLeftGoal)); 
    if (FirstTop<100){Firsttop=100;FirstTopGoal = 2 - Math.random()*4;}; 
    if (FirstLeft<50){FirstLeft=50;FirstLeftGoal = 2 - Math.random()*4;}; 
    if (FirstTop>130){Firsttop=130;FirstTopGoal = 2 - Math.random()*4;}; 
    if (FirstLeft>500){Firsttop=500;FirstLeftGoal = 2 - Math.random()*4;}; 
    $("#first").animate(
     {top: FirstTop,left:FirstLeft}, 
     {duration: 0, 
     easing: "linear"} 
    ); 
}; 
+0

你已經設置動畫持續時間爲0,所以我不知道你爲什麼期望它顯示流暢的動畫。 – JJJ

回答

-1

此代碼應解決您的問題:

var i = 1; 
var interval = setInterval(function(){ 
    if(i < 100) { 
     i++; 

     var FirstTop = (FirstTop + FirstTopGoal); 
     var FirstLeft= (FirstLeft+ (FirstLeftGoal)); 
     var SecondTop = (SecondTop+ (SecondTopGoal)); 
     var SecondLeft = (SecondLeft + (SecondLeftGoal)); 
     if (FirstTop<100){Firsttop=100;FirstTopGoal = 2 - Math.random()*4;}; 
     if (FirstLeft<50){FirstLeft=50;FirstLeftGoal = 2 - Math.random()*4;}; 
     if (FirstTop>130){Firsttop=130;FirstTopGoal = 2 - Math.random()*4;}; 
     if (FirstLeft>500){Firsttop=500;FirstLeftGoal = 2 - Math.random()*4;}; 

     $("#first").animate(
      { top: FirstTop, left:FirstLeft}, 
      {duration: 0, easing: "linear"} 
     ); 
    } 
    else if(i == 100){ 
     clearInterval(interval); 
    } 
}, 1); 

使用setInterval而不是for循環,因爲。 Here你可以在jsFiddle上看到一個例子。

如果您指定延遲爲0,那麼for循環比setInterval還要快。這是因爲setInterval的最小延遲值爲4ms。 也看這個問題:Why setTimeout(function, 0) is executed after next operation, but not in the moment of calling?

+0

更新了修復時間和緩動。請解釋downvote ... – erikscandola

+0

jQuery動畫會自動放入隊列中,所以信號量基本上什麼都不做。 – JJJ

+0

@Juhana你是對的!對不起,我忘了這個特點。我會更新我的代碼去除信號量。 – erikscandola