window.getComputedStyle()
window.getComputedstyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值,即返回一个包含所有最终css属性值的对象;
element.style也是获取元素css属性的,但是它只读取内联样式,即写在元素style属性上的样式;
getComputedStyle则读取最终样式,包括内联,嵌入,外联;
element.style支持读写,getComputedStyle只读;
我们可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式。
getComputedStyle 和 element.style 的相同点就是二者返回的都是 CSSStyleDeclaration 对象,取相应属性值得时候都是采用的 CSS 驼峰式写法,均需要注意 float 属性。
语法
let style = window.getComputedstyle(element, [pseudoElt]);
element
要获取计算样式的元素
let elem1 = document.getElementById("elemId");
let style = window.getComputedStyle(elem1);
pseudoElt | 可选
指定一个要匹配的伪元素的字符串,必须对普通元素省略(或null)
let elem1 = document.getElementById("elemId");
let style = window.getComputedStyle(elem1, '::hover')
返回值
getComputedStyle 返回的对象是 CSSStyleDeclaration 类型的对象
返回属性值。例如: valString= styleObj.getPropertyValue(‘color’)
CSS属性值可以使用getPropertyValue(propName)API或直接索引到对象,如cs [‘z-index’]或cs.zIndex。