javascript - 为什么初始 CSS 样式在 DOM element.style 字段上不可见?
问题描述
好的,我完全期望因为提出一些愚蠢的问题(或至少是重复的)而陷入困境,但是在附加的代码片段中,为什么我必须使用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>
解决方案
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>
推荐阅读
- parallel-processing - dask_ml.model_selection.GridSearchCV 关于并行计算的问题
- html - 粘性位置不适用于视口高度小于 500 像素
- heroku - 如何使用 http-proxy-middleware?客户端和服务器 api 没有通信
- iis - Swagger API 在部署到 IIS (.Net Framework) 后公开访问时返回 500 错误
- python - 如何在 MySQL 中查找包含任意数量的双引号和单引号的文本
- javascript - React Pdf pdf worker Path 必须是字符串。收到未定义的错误
- db2 - Db2 on Cloud:尝试添加服务凭证时“Service Broker 返回错误状态代码 500”
- python - 我可以输出动态时间扭曲的 wav 文件吗?
- chocolatey - 在 Windows Server 2019 数据中心上安装 Windows 终端
- node.js - 将无头 cms 中的 img 标签替换为 Next Image 组件