大网数据广告活动
Web 标准与前端开发

CSSStyleSheet: addRule() method

· 52CE 我爱测

The obsolete CSSStyleSheet interface's **`addRule()`** _legacy method_ adds a new rule to the stylesheet. You should avoid using this method, and should instead use the more standard CSSStyleSheet.insertRule method.

CSSOM

The obsolete CSSStyleSheet interface's addRule() legacy method adds a new rule to the stylesheet. You should avoid using this method, and should instead use the more standard CSSStyleSheet.insertRule method.

Syntax

addRule(selector, styleBlock, index)

Parameters

  • selector
    • : A string specifying the selector portion of the CSS rule. The default is the string undefined.
  • styleBlock
    • : A string indicating the style block to apply to elements matching the selector. 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).

Return value

Always returns -1.

Note that due to somewhat esoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. See CSSStyleSheet.insertRule for more information.

Usage notes

This method is implemented by browsers by constructing a string using the template literal `${selector}{${styleBlock}}`, then passing it into the standard CSSStyleSheet.insertRule method.

Therefore, given existing code such as the following:

cssStyleSheet.addRule(selector, styles, 0);

You can rewrite this to use the more standard insertRule() like this:

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

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。