Jon*_*ink 3 javascript css transition race-condition
我正在尝试创建一个操作,在其中创建一个 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
};
Run Code Online (Sandbox Code Playgroud)
当“go”按钮(参见 JSBin)被快速点击时,div 只会偶尔出现(大概是由于上述时间问题)。
如果您增加setTimeout的延迟值,您可以看到转换几乎总是有效。
有没有办法在创建元素后立即确定性地开始转换(而不必求助于延迟)?
对于转换,您需要两个不同的状态。变化。
两个渲染周期之间的样式只会被覆盖。它们仅在(重新)渲染节点时应用。
因此,如果您的 setTimeout() 在应用“旧”样式之前触发,则仅会覆盖 stlyes,并且您的节点会以目标样式呈现。
AFAIK。大多数(桌面)浏览器争取 60fps 的帧率,其间隔为 16.7ms。所以 setTimeout(fn,0) 很可能会在那之前触发。
您可以按照您提到的方式增加超时时间(我建议至少 50 毫秒),或者您可以触发/强制执行节点的渲染;例如通过询问它的大小。
要获得节点的大小,浏览器首先必须将所有样式应用于节点,以了解它们如何影响它。
此外,上下文对 css 很重要,因此必须将 Node 添加到 DOM 的某个位置,以便浏览器能够获得最终计算出的样式。
长回答短:
document.getElementById('go').onclick = function() {
var testdiv = createBlock();
testdiv.style.transition = "top 2.0s linear 0s";
testdiv.scrollWidth; //trigger rendering
//JsBin brags that you don't do anything with the value.
//and some minifyer may think it is irrelevant and remove it.
//so, increment it (`++`); the value is readonly, you can do no harm by that.
//but the mere expression, as shown, already triggers the rendering.
//now set the target-styles for the transition
testdiv.style.top = (defaultHeight*-2) + 'px';
};
Run Code Online (Sandbox Code Playgroud)