CSSStyleSheet: insertRule() 方法
CSSStyleSheet.insertRule() 方法将一个新的 CSS 规则 插入到 当前样式表 中。
注意: 尽管 insertRule() 仅是 CSSStyleSheet 的一个方法,但它实际上是将规则插入到 CSSStyleSheet.cssRules 中——也就是它的内部 CSSRuleList。
语法
js
insertRule(rule)
insertRule(rule, index)
参数
返回值
新插入规则在样式表规则列表中的索引。
异常
IndexSizeErrorDOMException-
如果
index>CSSRuleList.length,则抛出此错误。 HierarchyRequestErrorDOMException-
如果由于某些 CSS 约束(例如:尝试在样式规则之后插入
@importat-规则)而无法在指定索引处插入rule,则抛出此错误。 SyntaxErrorDOMException-
如果
rule参数中给出了多个规则,则抛出此错误。 InvalidStateErrorDOMException-
如果
rule是@namespace并且规则列表仅包含@importat-规则和/或@namespaceat-规则,则抛出此错误。
示例
插入新规则
此代码片段将一个新规则推送到我的样式表的顶部。
js
myStyle.insertRule("#blanc { color: white }", 0);
添加样式表规则的函数
js
/**
* Add a stylesheet rule to the document (it may be better practice
* to dynamically change classes, so style information can be kept in
* genuine stylesheets and avoid adding extra elements to the DOM).
* Note that an array is needed for declarations and rules since ECMAScript does
* not guarantee a predictable object iteration order, and since CSS is
* order-dependent.
* @param {Array} rules Accepts an array of JSON-encoded declarations
* @example
addStylesheetRules([
['h2', // Also accepts a second argument as an array of arrays instead
['color', 'red'],
['background-color', 'green', true] // 'true' for !important rules
],
['.myClass',
['background-color', 'yellow']
]
]);
*/
function addStylesheetRules(rules) {
const styleEl = document.createElement("style");
// Append <style> element to <head>
document.head.appendChild(styleEl);
// Grab style element's sheet
const styleSheet = styleEl.sheet;
for (let rule of rules) {
let i = 1,
selector = rule[0],
propStr = "";
// If the second argument of a rule is an array of arrays, correct our variables.
if (Array.isArray(rule[1][0])) {
rule = rule[1];
i = 0;
}
for (; i < rule.length; i++) {
const prop = rule[i];
propStr += `${prop[0]}: ${prop[1]}${prop[2] ? " !important" : ""};\n`;
}
// Insert CSS Rule
styleSheet.insertRule(
`${selector}{${propStr}}`,
styleSheet.cssRules.length,
);
}
}
规范
| 规范 |
|---|
| CSS 对象模型 (CSSOM) # dom-cssstylesheet-insertrule |
浏览器兼容性
加载中…
另见
CSSStyleSheet.deleteRule- 可构造样式表 (web.dev)