过时
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

过时 CSSStyleSheet 接口的 addRule() legacy method adds a new rule to the stylesheet. You should avoid using this method, and should instead use the more standard insertRule() 方法。

句法

var result = cssStyleSheet.addRule(selector, styleBlock, index);
					

参数

选择器
DOMString specifying the selector portion of the CSS rule. The default is the string undefined .
styleBlock
DOMString indicating the style block to apply to elements matching the 选择器 . The default is the string undefined .
index 可选
An optional index into the stylesheet's CSSRuleList at which to insert the new rule. If index is not specified, the next index after the last item currently in the list is used (that is, the value of cssStyleSheet.cssRules.length ).

返回值

Always returns -1.

Note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. See insertRule() 了解更多信息。

用法注意事项

This method is implemented by browsers by constructing a string using the template literal `${selector}{${styleBlock}}` , then passing it into the standard insertRule() 方法。

Therefore, given existing code such as the following:

cssStyleSheet.addRule(selector, styles, 0);
					

You can rewrite this to use the more standard insertRule() 像这样:

cssStyleSheet.insertRule(`${selector} {${styles}}`, 0);
					

规范

规范 状态 注释
CSS Object Model (CSSOM)
The definition of 'CSSStyleSheet.addRule()' in that specification.
工作草案

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
addRule() 弃用 Chrome Yes Edge 12 Firefox 68 IE 9 Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 68 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

弃用。不要用于新网站。

弃用。不要用于新网站。

另请参阅

元数据

  • 最后修改: