正如标题所说。我有这个代码: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.
关于javascript - css 过渡不透明度在元素显示 :none then changed to display:block 的地方不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548684/