Get the computed background color of an element:
const element = document.getElementById("test");
const cssObj = window.getComputedStyle(element, null);
let bgColor = cssObj.getPropertyValue("background-color");
Try it Yourself »
More examples below.
The getComputedStyle()
method gets the computed CSS properties and values of an HTML element.
The getComputedStyle()
method returns a CSSStyleDeclaration object
.
The computed style is the style used on the element after all styling sources have been applied.
Style sources: external and internal style sheets, inherited styles, and browser default styles.
window.getComputedStyle(
element, pseudoElement)
Parameter | Description |
element | Required. The element to get the computed style for. |
pseudoElement | Optional. A pseudo-element to get. |
Type | Description |
An object | A CSSStyleDeclaration object with all the CSS properties and values of the element. |
Get all the computed styles from an element:
const element = document.getElementById("test");
const cssObj = window.getComputedStyle(element, null);
let text = "";
for (x in cssObj) {
cssObjProp = cssObj.item(x)
text += cssObjProp + " = " + cssObj.getPropertyValue(cssObjProp) + "<br>";
}
Try it Yourself »
Get computed font size of the first letter in an element (using pseudo-element):
const element = document.getElementById("test"); const cssObj = window.getComputedStyle(element, ":first-letter")
let size = cssObj.getPropertyValue("font-size");
Try it Yourself »
getComputedStyle()
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!