【问题标题】:Why does my getComputedStyle console.logs initial values为什么我的 getComputedStyle console.logs 初始值
【发布时间】:2022-11-29 23:21:41
【问题描述】:

大家好,我想使用 getComputedStyle 来访问 css 属性,不幸的是它只有 console.log() 的标准属性。

下面你会找到我的代码。

在图片上,您会发现它注销的内容。

enter image description here

`


<body>
    <div id="box">box</div>


    <script>
        const box = document.getElementById("box");
        
        const boxCS = window.getComputedStyle(box)
        
        console.log(boxCS.zIndex)
        </script>
</body>

<style>
    #box {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    position: absolute;
    z-index: 1;
    background-color: rgb(200, 200, 200);
}
</style>

`

【问题讨论】:

  • 因为您将样式标签放在脚本标签之后(实际上在甚至无效的主体之外)。

标签: javascript html css getcomputedstyle


【解决方案1】:

在 DOM 渲染完成之前,您的脚本正在运行。尝试将您的预设包装在事件侦听器中。

例子

window.addEventListener("DOMContentLoaded", () => {
    const box = document.getElementById("box");
    const boxCS = window.getComputedStyle(box)
        
    console.log(boxCS.zIndex)
});

详情参考MDN documentation on DOMContentLoaded

【讨论】:

    【解决方案2】:

    原因之一是您在script 之后声明样式。 如果你把它放在script之前,就可以了。 Example

    【讨论】:

    • 如果您需要按原样保留 DOM,@idleberg 的答案会更好
    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2021-07-04
    相关资源
    最近更新 更多