CSSStyleDeclaration(样式声明对象)表示一个对象,它是一个CSS声明块,它公开样式信息以及各种与样式相关的方法和属性。
CSSStyleDeclaration对象表示CSS属性-值对的集合。
var heading = document.getElementsByTagName("h1")[0];
var output = document.getElementById("result");
function myFunc1() {
var styleObj = heading.style;
output.innerHTML = styleObj.cssText;
}
function myFunc2() {
var prop = window.getComputedStyle(heading, null).getPropertyValue("color");
output.innerHTML = prop;
}测试看看‹/›HTMLElement.style处理单个元素的内联样式。
window.getComputedStyle()将CSSStyleDeclaration对象公开为只读接口。
下表列出了CSSStyleDeclaration对象的属性:
| 属性 | 描述 |
|---|---|
| cssText | 设置或返回CSS声明块的文本表示形式 |
| length | 返回CSS声明块中的样式声明数 |
| parentRule | 返回作为样式块父级的CSS规则 |
下表列出了CSSStyleDeclaration对象的方法:
| 方法 | 描述 |
|---|---|
| getPropertyPriority() | 返回指定的CSS属性是否具有“!important”规则集 |
| getPropertyValue() | 返回指定CSS属性的值 |
| item() | 通过索引从CSS声明块返回CSS属性名称 |
| removeProperty() | 从CSS声明块中删除CSS属性 |
| setProperty() | 在CSS声明块中设置新的或修改现有的CSS属性 |