5

好的,我完全期望因为提出一些愚蠢的问题(或至少是重复的)而陷入困境,但是在附加的代码片段中,为什么我必须使用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>

4

2 回答 2

8

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>

于 2019-01-23T07:04:30.427 回答
5

HTMLElement.style用于元素的内联样式。它不考虑CSS。这基本上只是直接设置或获取元素对象的属性。

<div style="color: red;">Hello</div>

Window.getComputedStyle()考虑到内联样式CSS,在解决级联、继承等问题后。它基本上是用于在页面上呈现元素的“最终”实际样式值。

// CSS
#blue-text {
  color: blue !important;
}

// HTML
<div style="color: red;" id="blue-text">Hello</div>

// JS
const myElement = document.querySelector("#blue-text");
myElement.style.color; // "red" because that's the inline style
window.getComputedStyle(myElement).color; // "rgb(0, 0, 255)" because CSS !important overrides inline style
于 2019-01-23T07:00:10.013 回答