--- title: CSSStyleDeclaration slug: Web/API/CSSStyleDeclaration tags: - API - CSSOM - 参考 - 接口 translation_of: Web/API/CSSStyleDeclaration --- <p>{{ APIRef("CSSOM") }}</p> <p><strong><code>CSSStyleDeclaration</code></strong> 接口表示一个对象,它是一个 CSS 声明块,CSS 属性键值对的集合。它暴露了样式信息和各种与样式相关的方法和属性。</p> <p><code>CSSStyleDeclaration</code> 对象可被暴露于三种不同的 API 下:</p> <ul> <li>{{domxref("HTMLElement.style")}},用于操作单个元素的样式(<code><elem style="..."></code>)。</li> <li>{{domxref("CSSStyleSheet")}} API,举个例子,<code>document.styleSheets[0].cssRules[0].style</code> 会返回文档中第一个样式表中的第一条 CSS 规则。</li> <li>{{domxref("Window.getComputedStyle()")}},将 <code>CSSStyleDeclaration</code> 对象作为一个<strong>只读</strong>的接口。</li> </ul> <h2 id="属性">属性</h2> <dl> <dt>{{domxref("CSSStyleDeclaration.cssText")}}</dt> <dd>当前声明块的文本内容。设置此属性会改变样式。</dd> <dt>{{domxref("CSSStyleDeclaration.length")}}</dt> <dd>属性的数量。参照下面的 {{domxref("CSSStyleDeclaration.item()", 'item()')}} 方法。</dd> <dt>{{domxref("CSSStyleDeclaration.parentRule")}}</dt> <dd>包含当前声明块的 {{domxref("CssRule")}}。</dd> </dl> <h2 id="方法">方法</h2> <dl> <dt>{{domxref("CSSStyleDeclaration.getPropertyPriority()")}}</dt> <dd>返回可选的优先级,"important"。</dd> <dt>{{domxref("CSSStyleDeclaration.getPropertyValue()")}}</dt> <dd>返回给定属性的值。</dd> <dt>{{domxref("CSSStyleDeclaration.item()")}}</dt> <dd>返回用index标记的属性名,当index越界时返回空字符串。</dd> <dd>另一个可选方案:使用nodeList[<var>i</var>](在i越界时返回 undefined)获取。通常在非JavaScript Dom 实现方案是很有用。</dd> <dt>{{domxref("CSSStyleDeclaration.removeProperty()")}}</dt> <dd>从 CSS 声明块中删除属性。</dd> <dt>{{domxref("CSSStyleDeclaration.setProperty()")}}</dt> <dd>在CSS声明块中修改现有属性或设置新属性。</dd> <dt>{{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}} {{obsolete_inline}}</dt> <dd><strong>仅在火狐浏览器中支持 getComputedStyle.</strong> 返回 {{ domxref("CSSPrimitiveValue") }} or <code>null</code> for <a href="/en-US/docs/Web/CSS/Shorthand_properties" title="en/Guide to Shorthand CSS">shorthand properties</a>.</dd> </dl> <h2 id="范例">范例</h2> <pre class="brush: js notranslate">var styleObj = document.styleSheets[0].cssRules[0].style; console.log(styleObj.cssText); for (var i = styleObj.length; i--;) { var nameString = styleObj[i]; styleObj.removeProperty(nameString); } console.log(styleObj.cssText);</pre> <h2 id="规范">规范</h2> <table class="standard-table"> <thead> <tr> <th scope="col">规范</th> <th scope="col">状态</th> <th scope="col">备注</th> </tr> </thead> <tbody> <tr> <td>{{SpecName('CSSOM', '#the-cssstyledeclaration-interface', 'CSSStyleDeclaration')}}</td> <td>{{Spec2('CSSOM')}}</td> <td></td> </tr> <tr> <td>{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSStyleDeclaration')}}</td> <td>{{Spec2('DOM2 Style')}}</td> <td>Initial definition</td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>{{Compat("api.CSSStyleDeclaration")}}</p> <h2 id="参见">参见</h2> <ul> <li><a href="/zh-CN/docs/Web/CSS/CSS_Properties_Reference">DOM CSS Properties</a></li> </ul>