Part1element.style
过去我们学习dom的时候,获取样式和设置样式是这样的。
<h1 style="color: aqua;">标题</h1>
const h1Dom = document.getElementsByTagName('h1')[0];
// 获取
const color = h1Dom.style.color
// 赋值
h1Dom.style.color = 'red';
但是她有一定的缺陷。因为它只能获取元素的内联样式,即写在元素的 style 属性上的样式。看看下面两个示例:
示例1
// css
h1{
color: #008B8B;
}
<h1 style="color: aqua;">标题</h1>
const h1Dom = document.getElementsByTagName('h1')[0];
h1Dom.style.color // aqua
示例2
// css
h1{
color: #008B8B;
}
<h1>标题</h1>
const h1Dom = document.getElementsByTagName('h1')[0];
h1Dom.style.color // 空
这里我们可以看出来,xxx.style获取只能获取行内样式。其它获取不了。
Part2window.getComputedStyle()
getComputedStyle 返回的对象是 CSSStyleDeclaration 类型的对象。取数据的时候可以直接按照属性的取法去取数据,例如 style.backgroundColor。需要注意的是,返回的对象的键名是 css 的驼峰式写法,background-color -> backgroundColor。
示例1
// css
h1 {
font-size: 30px;
}
<h1 style="font-size: 20px;">标题</h1>
const h1Dom = document.getElementsByTagName('h1')[0];
const style = window.getComputedStyle(h1Dom);
style.fontSize // 20px
示例2
// css
h1 {
font-size: 30px;
}
<h1>标题</h1>
const h1Dom = document.getElementsByTagName('h1')[0];
const style = window.getComputedStyle(h1Dom);
style.fontSize // 30px
Part3style与getComputedStyle异同
相同点 | 不同点 |
---|---|
1、二者返回的都是 CSSStyleDeclaration 对象,取相应属性值得时候都是采用的 CSS 驼峰式写法 | 1、element.style 读取的只是元素的内联样式,即写在元素的 style 属性上的样式;而 getComputedStyle 读取的样式是最终样式,包括了内联样式、嵌入样式和外部样式。 2、element.style 既支持读也支持写,我们通过 element.style 即可改写元素的样式。而 getComputedStyle 仅支持读并不支持写入。我们可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式 |