1 回答

TA贡献1784条经验 获得超7个赞
这是因为setTimeout(/**/, 0)不保证回调将在后续帧上执行。这可能(取决于浏览器实现和计算机速度)导致将样式应用于与插入到 DOM 中的节点相同的框架。
理论上,您应该使用requestAnimationFrameinstead,这正是针对此类情况的。
但是,在您链接的小提琴中,只有当我将requestAnimationFrame难以察觉但仍然不受欢迎的加倍时它才有效......如果它是 JSFiddle 的侥幸或什么......
function move(color){
let clone=document.getElementById("test").cloneNode(true);
clone.id=color;
clone.style.display="block";
clone.style.backgroundColor=color;
document.getElementById("main").prepend(clone);
requestAnimationFrame(() => {
requestAnimationFrame(() => {
clone.style.left="500px";
})
})
}
这是一个片段:
function move(color) {
let clone = document.getElementById("test").cloneNode(true);
clone.id = color;
clone.style.display = "block";
clone.style.backgroundColor = color;
document.getElementById("main").prepend(clone);
requestAnimationFrame(() => {
requestAnimationFrame(() => {
clone.style.left = "500px";
})
})
}
setTimeout(() => move("red"), 500);
setTimeout(() => move("green"), 750);
#main {
display: block;
width: 100vw;
height: 100vh;
background-color: blue;
}
.test {
position: absolute;
display: none;
width: 100px;
height: 100px;
background-color: red;
transition: left 1s ease;
transform: scale(1);
left: 0px;
}
<div id="main"></div>
<div id="test" class="test"></div>
添加回答
举报