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