Window.getComputedStyle()
方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有 CSS 属性的值。私有的 CSS 属性值可以通过对象提供的 API 或通过简单地使用 CSS 属性名称进行索引来访问。
getComputedStyle语法:
let style = window.getComputedStyle(element, [pseudoElt]);
//第一个参数是指定元素的dom对象
//pseudoElt伪元素拉取样式信息 比如, ::after, ::before, ::marker, ::line-marker。非必需
返回值:CSSStyleDeclaration - Web API 接口参考 | MDN
属性
CSSStyleDeclaration.cssText (en-US)
当前声明块的文本内容。设置此属性会改变样式。
CSSStyleDeclaration.length
属性的数量。参照下面的 item() 方法。
CSSStyleDeclaration.parentRule (en-US)
包含当前声明块的 CssRule。
方法
CSSStyleDeclaration.getPropertyPriority()
返回可选的优先级,"important"。
CSSStyleDeclaration.getPropertyValue()
返回给定属性的值。
CSSStyleDeclaration.item()
返回用 index 标记的属性名,当 index 越界时返回空字符串。 另一个可选方案:使用 nodeList[i](在 i 越界时返回 undefined)获取。通常在非 JavaScript Dom 实现方案是很有用。
CSSStyleDeclaration.removeProperty()
从 CSS 声明块中删除属性。
CSSStyleDeclaration.setProperty()
在 CSS 声明块中修改现有属性或设置新属性。
CSSStyleDeclaration.getPropertyCSSValue() 已弃用
仅在火狐浏览器中支持 getComputedStyle. 返回 CSSPrimitiveValue (en-US) or null
for shorthand properties.
let elem1 = document.getElementById("elemId");
let style = window.getComputedStyle(elem1, null);
let paddingL = parseFloat(style.getPropertyValue('padding-left')); //获取左侧内边距
let paddingR = parseFloat(style.getPropertyValue('padding-right')); //获取右侧内边距
let w = parseFloat(style.getPropertyValue('width')); // 获取实际宽度
let concentW = Number(w = paddingL - paddingR ); //实际内容宽度
与伪元素一起使用:
<style>h3::after {content: "rocks!";}
</style><h3>generated content</h3><script>let h3 = document.querySelector("h3"),result = getComputedStyle(h3, "::after").content;alert(`the generated content is: ${result}`);console.log(`the generated content is: ${result}`);// the generated content is: "rocks!"
</script>