2017-04-13 41 views
0

有什麼方法可以等到應用CSS DOM更改?同步從jQuery運行CSS動畫

下面是一個例子:

CSS:

.box { 
    width: 100px; 
    height: 100px; 
    background: red; 
} 

.anim { 
    transition: transform 2s; 
} 

HTML:

<div class="box"></div> 

的jQuery:

$(".box").css("transform", "translate3d(200px,0,0)"); 
$(".box").addClass("anim"); 
$(".box").css("transform", "translate3d(210px,0,0)"); 

的jsfiddle演示:https://jsfiddle.net/tfxbej9q/

我期望的<div>跳轉到位置200,然後啓用動畫並且瀏覽器平滑移動<div> 10px到右邊(位置210)。

會發生什麼<div>順暢地從位置0移到210

我的解決方案(但我不喜歡它):有

$(".box").css("transform", "translate3d(200px,0,0)"); 
setTimeout(function() { 
     $(".box").addClass("anim"); 
     $(".box").css("transform", "translate3d(210px,0,0)"); 
}, 10); 

是任何功能:添加setTimeout功能等到DOM更改應用?

+0

這不是jQuery的動畫。如果你想使用這個庫,他們有一個易於使用的animate()方法。 http://api.jquery.com/animate/ – cgTag

回答

0

幾周前我有同樣的問題,並使用window.requestAnimationFrame來解決它。

這不是一個真正的jQuery問題,這是瀏覽器試圖保存重繪。解決這個問題的唯一方法是強制瀏覽器使用2重繪,或者使用timeout/requestAnimationFrame/.delay(1)或者通過強制重新計算類似於offsetHeight的樣式來重繪。

$(".box").css("transform", "translate3d(200px,0,0)"); 
window.requestAnimationFrame(function(){ 
    $(".box").addClass("anim"); 
    $(".box").css("transform", "translate3d(210px,0,0)"); 
}); 

它看起來很像您的超時解決方案。 jsfiddle example

$(".box").css("transform", "translate3d(200px,0,0)"); 
$(".box").get(0).offsetHeight; 
$(".box").addClass("anim"); 
$(".box").css("transform", "translate3d(210px,0,0)"); 

jsfiddle example

mgHenry做了一個小擴展到jQuery來使這個看起來有點更好在你的代碼https://gist.github.com/mgHenry/6154611