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

标签 javascript css stylesheet getcomputedstyle

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

如果不是,控制哪些属性(以及何时)反射(reflect)在元素的 .style 中的确切规则是什么? field ?

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>

最佳答案

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属性用于获取 以及 设置 内联样式 的一个元素。

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>

关于javascript - 为什么初始 CSS 样式在 DOM element.style 字段上不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54321532/

相关文章:

javascript - CSS:Hover 的文本问题因为溢出而被隐藏:隐藏?

JavaScript html setter "eats"文本区域内的前导换行符 - 如何克服?

css - 如何为移动设备包装三个div

html - img 上不透明度的 CSS 关键帧动画不起作用

jquery - 白线故障(25% 大小的 div)

javascript - 如何设置输入:focus style programatically using JavaScript

javascript - 在 FormView 的 Edittemplate 中显示 Google map 时遇到问题

javascript - 使用特殊字符时无法获得 if ... else 语句来正确切换 ("⏶/⏷")

javascript - 使用 NodeJS 在 mysql 中插入关系表的最佳方法是什么

css - 不同浏览器对css文件的大小和数量有什么限制?