2016-08-18 20 views
1

每個動畫完成後,我將div移動到子列表的末尾。只有在第一個complete函數運行後,在下一個動畫運行之前有一段延遲。在所有其他人之後,沒有任何延遲。爲什麼這個動畫僅在第一步之後纔會延遲?

爲什麼第一個延遲?

https://jsfiddle.net/cev2Lh9w/

HTML

<div class="outer"> 
<div class="test"> 
test 
</div> 
<div class="test"> 
test 
</div> 
<div class="test"> 
test 
</div> 
<div class="test"> 
test 
</div> 
</div> 

的Javascript

jQuery(document).ready(
function() 
{ 
window.doms = document.querySelectorAll(".test"); 
window.self = document.querySelector(".outer"); 
window.currentTile = doms[ 0 ]; 
window.currentMove = 0; 
window.numberToMove = 20; 
window.tileHeight = 20; 
window.currentIndex = 0; 
console.log(self); 
moveNext(); 
}); 

function finishMove() 
    { 
     //Move the top tile to the end 
     self.appendChild(currentTile); 

     //Adjust its top 
     currentTile.style.marginTop = "0px"; 

     //The next tile 
     var next = doms[ currentIndex ]; 

     //Update current move and tile 
     currentMove++; 
     currentTile = next; 

     //Change the current index 
     currentIndex = (currentIndex === doms.length - 1) ? 0 : currentIndex += 1; 

     //Move again 
     if (currentMove < numberToMove) moveNext(); 

     //We're done 
     else alert("done"); 
    } 

    function moveNext() 
    { 
     //Animate the sliding 
     jQuery(currentTile).animate(
      { 
       marginTop: "-" + tileHeight + "px" 
      }, 
      { 
       duration: 200, 
       queue: false, 
       complete: finishMove 
      } 
     ); 
    }; 
+0

我知道這並沒有太大的幫助,卜如果你的代碼'window.currentIndex = 0更改;''到window.currentIndex = 1;'那遲遲不露面。我仍然不確定爲什麼。但它似乎與該陣列的第一個元素有關,儘管... – n0m4d

+0

@ n0m4d我不知道爲什麼,但看到我的答案是如何修復它的。雖然 –

回答

0

這似乎是jQuery的包裝的建設。如果我將它們緩存在一個數組中,然後使用該數組的jquery對象,則不會有任何延遲。

https://jsfiddle.net/cev2Lh9w/1/

//Save them as jQuery objects 
window.jDoms = []; 
for (var i = 0; i < doms.length; i++) jDoms.push(jQuery(doms[ i ])); 

... 

//Call animate on the pre-build jQuery object 
jDoms[ currentIndex ].animate(...) 
+1

好點!不過,如果從第二個元素開始,動畫中的「流動性」看起來更「自然」。檢查[this](https://jsfiddle.net/cev2Lh9w/2/)小提琴看到我的觀點。 – n0m4d

+0

@ n0m4d這真的很奇怪。我想知道爲什麼,但不能想到一個理由 –

相關問題