css到底是什么时候渲染的?

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>

<body>
<div id="box"> 
</div>
</body>
<script>
    window.onload = function () {
        let box = document.querySelector("#box")
        console.log(box.style)
    }
</script>
</html>

为什么在onload事件里面打印box.style,里面的属性值还都是空的呢

clipboard.png

阅读 2k
1 个回答
HTMLElement.style 属性返回一个 CSSStyleDeclaration 对象,表示元素的 内联style 属性(attribute),但忽略任何样式表应用的属性。

...

通常,要了解元素样式的信息,仅仅使用 style 属性是不够的,这是因为它只包含了在元素内嵌 style 属性(attribute)上声明的的 CSS 属性,而不包括来自其他地方声明的样式,如 <head> 部分的内嵌样式表,或外部样式表。要获取一个元素的所有 CSS 属性,你应该使用 window.getComputedStyle()

HTMLElement.style - Web API 接口参考 | MDN

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题