我試圖創建一個動作,創建一個div並立即向上「浮動」,直到它離開屏幕。在元素創建後立即觸發轉換
爲了做到這一點,我試圖使用CSS transition,這將完全由JavaScript驅動(由於我的使用情況的限制)。
當我創建一個元素,爲其分配轉換樣式屬性,然後立即嘗試通過改變樣式來啓動轉換(top
)時,會出現問題。
看起來像一個時間問題正在發生,其中top
風格變化在轉換變爲可用之前觸發,因此只需立即將我的div移出屏幕,而不是實際執行轉換。
下面是一個簡化的例子:
var
defaultHeight = 50,
iCount = 0,
aColors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
function createBlock() {
var testdiv = document.createElement('div');
testdiv.className = 'testdiv';
document.body.appendChild(testdiv);
testdiv.style.left = '50%';
testdiv.style.backgroundColor = aColors[iCount % aColors.length];
testdiv.style.width = defaultHeight + 'px';
testdiv.style.height = defaultHeight + 'px';
testdiv.style.fontSize = '30px';
testdiv.style.textAlign = 'center';
testdiv.innerHTML = iCount;
testdiv.style.top = '500px';
testdiv.style.position = 'absolute';
iCount++;
return testdiv;
}
document.getElementById('go').onclick = function() {
var testdiv = createBlock();
testdiv.style.transition = "top 2.0s linear 0s";
setTimeout(function() {
testdiv.style.top = (defaultHeight*-2) + 'px';
}, 0); // <- change this to a higher value to see the transition always occur
};
當「去」按鈕(see JSBin)被點擊迅速在div只出現零星(推測是由於上述的定時問題)。
如果你增加setTimeout
的延遲值,你可以看到轉換幾乎總是有效的。
有沒有一種方法可以確定性地在創建元素後立即啓動轉換(而不必求助於延遲)?
你需要在一個類中添加動畫(新)最高值,並將其賦值類代替,否則過渡不知道哪個頂部之間因爲後者動畫價值覆蓋前者。 – LGSon
@LGSon新創建的div給出了'500px'的初始頂部值...爲什麼需要在CSS類中定義(除了作爲最佳實踐)? –
誤讀你的問題有點...會在一秒內發佈答案。 – LGSon