为什么初始的CSS样式在DOM element.style字段中不可见? [英] why are initial CSS styles not visible on DOM element.style field?

查看:105
本文介绍了为什么初始的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字段中不可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆