why are initial CSS styles not visible on DOM element.style field?(为什么初始的CSS样式在DOM element.style字段中不可见?)
问题描述
好吧,如果我问一些愚蠢的事情(或者至少是重复的),我完全有可能会失败,但在附加的代码片段中,为什么我必须使用window.getComputedStyle
来访问由css应用的样式?我的印象是.style
字段至少会反映那些最初由css应用的样式,和/或自那以后手动更改的样式。
如果不是,控制元素的.style
字段中反映哪些属性(以及何时)的确切规则是什么?
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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属性对完全 了解应用于元素的样式,因为它表示 只有在元素的内联样式中设置的CSS声明 属性,而不是来自其他地方样式规则的属性,如 节中的样式规则或外部样式表。为了得到 您应该使用的元素的所有css属性的值 改为Window.getComputedStyle()。 VIA-MDN Web Docs|获取样式 信息
HTMLElement.style:
HTMLElement.style属性用于获取以及设置元素的内联样式。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">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属性。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">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>
这篇关于为什么初始的CSS样式在DOM element.style字段中不可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么初始的CSS样式在DOM element.style字段中不可见?


- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01