【发布时间】:2017-05-15 10:34:59
【问题描述】:
在 JavaScript 中将元素的高度设置为 0,然后立即将其更改为特定值时,该元素的 CSS 过渡不起作用。
但是,通过将代码放置在 setTimeout() 内增加高度,即使延迟为 0,转换也可以正常工作,如下面的 sn-p 所示:
// 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);
div {
display: inline-block;
width: 200px;
background-color: black;
transition: height 1s;
}
#two {
background-color: blue;
}
<div id="one">
</div>
<div id="two">
</div>
此行为在所有主要浏览器中都是一致的。这样做的问题是,有时,似乎存在某种滞后,这使得解决方法也没有动画效果。所以这似乎不是一个干净的解决方案。
是什么导致转换取消,我怎样才能彻底解决这个问题?
【问题讨论】:
-
setTimeout(..., 0)并不是真正的0超时,而是更像setTimeout(..., asSoonAsYouHaveTimeForThatButAtLeast(10))
标签: javascript css css-transitions css-animations