首页 > 解决方案 > 为什么初始 CSS 样式在 DOM element.style 字段上不可见?

问题描述

好的,我完全期望因为提出一些愚蠢的问题(或至少是重复的)而陷入困境,但是在附加的代码片段中,为什么我必须使用window.getComputedStyle来访问 CSS 应用的样式?我的印象是,该.style字段至少会反映 CSS 最初应用的那些样式,和/或从那时起手动更改的那些样式。

.style如果不是,那么在元素的字段中反映(以及何时)反映哪些属性的确切规则是什么?

setTimeout(() => {
    console.log("the bckg color:", reddish.style.backgroundColor);
    console.log("the width:", reddish.style.width);
    console.log("from a computed style:", window.getComputedStyle(reddish).backgroundColor);
    console.log("from a computed style:", window.getComputedStyle(reddish).width);
}, 100);
#reddish {
    background-color: #fa5;
    width: 100px;
    height: 100px;
}
<html>
    <body>
        <div id="reddish"></div>
    </body>
</html>

标签: javascriptcssstylesheetgetcomputedstyle

解决方案


HTMLElement.style属性对于完全了解应用于元素的样式没有用处,因为它仅表示元素的内联样式属性中设置的 CSS 声明不是来自其他地方的样式规则的那些声明,例如该部分中的样式规则,或外部样式表。要获取元素的所有 CSS 属性的值,您应该使用 Window.getComputedStyle()代替。

Via- MDN 网络文档 | 获取样式信息


HTMLElement.style:

HTMLElement.style属性用于获取设置元素内联样式

console.log(document.getElementById("para").style.fontSize); // will work since the "font-size" property is set inline
console.log(document.getElementById("para").style.color); // will not work since the "color" property is not set inline
#para {color: rgb(34, 34, 34);}
<p id="para" style="font-size: 20px;">Hello</p>


Window.getComputedStyle():

然而, getComputedStyle()方法返回一个包含元素所有 CSS 属性值的对象,在应用活动样式表并解决这些值可能包含的任何基本计算之后,因此从内联样式声明和外部样式返回 css 属性-床单。

console.log(window.getComputedStyle(document.getElementById("para")).fontSize); // will work
console.log(window.getComputedStyle(document.getElementById("para")).color); // will work
#para {
  color: rgb(34, 34, 34);
}
<p id="para" style="font-size: 20px;">Hello</p>


推荐阅读