问题描述
正如标题所说.我有这个代码:https://jsfiddle.net/fwo9ym1o/
Like the title said. I have this code: 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;
并且转换没有发生.
So, I've changed the container.style.display = "block";
then applied container.style.opacity = 1;
and the transition is not happening.
如果我在新线程中运行所有内容,它会起作用.
It works if I run everything in a new thread.
注意:我不能使用可见性.它必须是 display:none
推荐答案
这是因为设计风格的方式.样式更改的开销很大,因此可以有效地保存它们,直到需要它们为止(调用像 .offsetHeight
这样的重新计算检查或需要绘制下一帧).
It's because of the way styles are figured out. Style changes are expensive so they are effectively saved up until they are needed (a recalc check like .offsetHeight
is called or the next frame needs to be drawn).
以下代码应该可以工作.它包括对(我认为)正在发生的事情的解释:
The following code should work. It includes an explanation of what (I think) is going on:
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.
这篇关于css 过渡不透明度在元素具有 display:none 然后更改为 display:block 的地方不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!