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)