--- title: HTMLElement.style slug: Web/API/ElementCSSInlineStyle/style translation_of: Web/API/ElementCSSInlineStyle/style original_slug: Web/API/HTMLElement/style ---
HTMLElement.style 属性返回一个 CSSStyleDeclaration 对象,表示元素的 内联style 属性(attribute),但忽略任何样式表应用的属性。 通过 style 可以访问的 CSS 属性列表,可以查看 CSS Properties Reference。
由于 style 属性的优先级和通过style设置内联样式是一样的,并且在css层级样式中拥有最高优先级,因此在为特定的元素设置样式时很有用。
style 属性注意不能通过直接给style属性设置字符串(如:elt.style = "color: blue;")来设置style,因为style应被当成是只读的(尽管Firefox(Gecko), Chrome 和 Opera允许修改它),这是因为通过style属性返回的CSSStyleDeclaration对象是只读的。但是style属性本身的属性能够用来设置样式。此外,通过单独的样式属性(如elt.style.color = '...')比用elt.style.cssText = '...' 或者 elt.setAttribute('style', '...')形式更加简便,除非你希望完全通过一个单独语句来设置元素的全部样式,因为通过style本身属性设置的样式不会影响到通过其他方式设置的其他css属性的样式。
// 在单个语句中设置多个样式
elt.style.cssText = "color: blue; border: 1px solid black";
// 或者
elt.setAttribute("style", "color:red; border: 1px solid blue;");
// 设置特定样式,同时保持其他内联样式值不变
elt.style.color = "blue";
通常,要了解元素样式的信息,仅仅使用 style 属性是不够的,这是因为它只包含了在元素内嵌 style 属性(attribute)上声明的的 CSS 属性,而不包括来自其他地方声明的样式,如 {{HTMLElement("head")}} 部分的内嵌样式表,或外部样式表。要获取一个元素的所有 CSS 属性,你应该使用 {{domxref("window.getComputedStyle()")}}。
<!DOCTYPE HTML>
<html>
<body style="font-weight:bold;">
<div style="color:red" id="myElement">..</div>
</body>
</html>
下面的代码输出 style 所有属性的名字,以及为元素 elt 显式设置的属性值和继承的计算值(computed value):
var element = document.getElementById("myElement");
var out = "";
var elementStyle = element.style;
var computedStyle = window.getComputedStyle(element, null);
for (prop in elementStyle) {
if (elementStyle.hasOwnProperty(prop)) {
out += " " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
}
}
console.log(out)
输出结果如下:
... fontWeight = '' > 'bold' color = 'red' > 'rgb(255, 0, 0)' ...
请注意,计算样式中font-weight的值为“bold”,元素的style属性中缺少该值
DOM Level 2 Style: ElementCSSInlineStyle.style
{{Compat("api.HTMLElement.style")}}