【发布时间】:2016-05-24 01:26:25
【问题描述】:
我正在尝试创建一个操作,其中创建一个 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 新创建的 div 的初始
top值为 '500px'...为什么需要在 CSS 类中定义(而不是作为最佳实践)? -
稍微误读了您的问题...将在几秒钟内发布答案。
标签: javascript css transition race-condition