正如标题所说。我有这个代码:https://jsfiddle.net/fwo9ym1o/
//javascript
var container = document.querySelector("#container");
container.style.display = "block";
//this is not working
//container.style.opacity = 1;
//this is working
setTimeout(function() {
container.style.opacity = 1;
}, 0);
/css
.container {
height: 200px;
width: 200px;
background-color: salmon;
display: none;
border-radius: 5px;
opacity: 0;
transition: opacity 2s ease-in-out;
}
//html
<div id="container" class="container"></div>
所以,我改变了container.style.display = "block";
然后应用container.style.opacity = 1;
并且转变并没有发生。
如果我在新线程中运行所有内容,它就会起作用。
注意:我无法使用可见性。必须显示:无
这是因为风格的确定方式。样式更改的成本很高,因此它们会被有效地保存起来,直到需要它们为止(重新计算检查,例如.offsetHeight
被调用或者需要绘制下一帧)。
下面的代码应该可以工作。它包括对(我认为)正在发生的事情的解释:
container.style.display = "block";
// container is actually still invisible
// current style hasn't been calculated
container.offsetHeight;
// this forces a style recalc
// so the current style for the container is figured out.
// without this recalc, this element effectively has no style,
// and so when you transition from its current style (null) to a different one (opacity: 1), it just snaps to the new value.
container.style.opacity = 1;
// this triggers the transition.
// because the style was recalced before the transition was triggered,
// it will transition _from_ those values.
jsFiddle
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)