Sim*_*son 9 javascript css css3 css-transitions css-animations
在JavaScript中将元素的高度设置为0然后立即将其更改为特定值时,元素的CSS转换不起作用.
但是,通过放置代码来增加a内的高度setTimeout(),即使延迟为0,转换仍然有效,如下面的代码片段所示:
// Doesn't work:
document.getElementById("one").setAttribute("style", "height: 0px");
document.getElementById("one").setAttribute("style", "height: 200px");
// Works:
document.getElementById("two").setAttribute("style", "height: 0px");
setTimeout(function() {
document.getElementById("two").setAttribute("style", "height: 200px");
}, 0);Run Code Online (Sandbox Code Playgroud)
div {
display: inline-block;
width: 200px;
background-color: black;
transition: height 1s;
}
#two {
background-color: blue;
}Run Code Online (Sandbox Code Playgroud)
<div id="one">
</div>
<div id="two">
</div>Run Code Online (Sandbox Code Playgroud)
此行为在所有主流浏览器中都是一致的.这个问题是,有时似乎存在某种延迟,这使得解决方法也不具有动画效果.所以这似乎不是一个干净的解决方案.
导致过渡取消的原因是什么?我如何干净利落地解决这个问题?
大多数情况下,浏览器会优化转换,并合并少于16毫秒的更改(这将使您的刷新率达到每秒约60帧)
因此,解决方案是简单地换行嵌套RAF调用的样式更改(告诉浏览器在准备就绪时的动画,而不是在任意超时之后)
window.requestAnimationFrame(function(){
document.getElementById("two").setAttribute("style", "height: 0px");
window.requestAnimationFrame(function(){
document.getElementById("two").setAttribute("style", "height: 200px");
});
});
Run Code Online (Sandbox Code Playgroud)
参考:https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame