CSSStyleSheet: insertRule() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

CSSStyleSheet.insertRule() 方法將一個新的 CSS 規則 插入到 當前樣式表 中。

注意: 儘管 insertRule() 僅是 CSSStyleSheet 的一個方法,但它實際上是將規則插入到 CSSStyleSheet.cssRules 中——也就是它的內部 CSSRuleList

語法

js
insertRule(rule)
insertRule(rule, index)

引數

rule

包含要插入規則的字串。要插入的規則必須包含什麼取決於其型別

  • 對於 規則集,需要同時包含一個 選擇器 和一個樣式宣告。
  • 對於 at-規則,需要同時包含一個 at-識別符號和規則內容。
index 可選

一個小於或等於 stylesheet.cssRules.length 的正整數,表示新插入規則在 CSSStyleSheet.cssRules 中的位置。預設為 0。(在舊的實現中,這是必需的。有關詳細資訊,請參閱 瀏覽器相容性。)

返回值

新插入規則在樣式表規則列表中的索引。

異常

IndexSizeError DOMException

如果 index > CSSRuleList.length,則丟擲此錯誤。

HierarchyRequestError DOMException

如果由於某些 CSS 約束(例如:嘗試在樣式規則之後插入 @import at-規則)而無法在指定索引處插入 rule,則丟擲此錯誤。

SyntaxError DOMException

如果 rule 引數中給出了多個規則,則丟擲此錯誤。

InvalidStateError DOMException

如果 rule@namespace 並且規則列表僅包含 @import at-規則和/或 @namespace at-規則,則丟擲此錯誤。

示例

插入新規則

此程式碼片段將一個新規則推送到我的樣式表的頂部。

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

瀏覽器相容性

另見