为什么初始 CSS 样式在 DOM element.style 字段中不可见?

why are initial CSS styles not visible on DOM element.style field?

好吧,我完全希望因为提出一些愚蠢的问题(或至少是重复的)而火上浇油,但是在附加的代码片段中,为什么我必须使用 window.getComputedStyle 来访问 [= 应用的样式30=]?我的印象是 .style 字段至少会反映那些最初由 CSS 应用的样式,and/or 从那时起手动更改。

如果不是,那么管理在元素的 .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>

HTMLElement.style 用于 inline style of an element。它不考虑任何 CSS。这基本上就是直接在元素对象上设置或获取一个属性。

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

Window.getComputedStyle()考虑了inline styles and CSS,在解决级联、继承等问题后,基本上就是"final"用于在页面上渲染元素的实际样式值。

// 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

The HTMLElement.style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets. To get the values of all CSS properties for an element you should use Window.getComputedStyle() instead.

Via- MDN Web Docs | Getting Style Information


HTMLElement.style:

HTMLElement.style属性用于get以及设置元素的内联样式

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() 方法然而, returns 包含元素所有 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>