javascript - css 过渡不透明度在元素显示 :none then changed to display:block 的地方不起作用

标签 javascript html css

正如标题所说。我有这个代码: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

关于javascript - css 过渡不透明度在元素显示 :none then changed to display:block 的地方不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548684/

相关文章:

javascript - 如何检查电话是否为: area code is correct using jquery?

javascript - 使用 Fleck 的 WebSocket。 WSS

html - CSS:如何计算流体布局的div内的边距

javascript - 我怎样才能让文本在另一个元素的鼠标悬停时发光(没有文本阴影)

javascript - 防止 window.opener.location.href 表单重新加载父级

javascript - 如何替换 css 类内容?

php - Symfony2 禁用 HTML5 表单验证

html - 删除表格图像之间的填充

javascript - Chrome RGBA 问题

html - 移动 webkit 渐变背景?