CSSStyleSheet.insertRule()

 
概述

insertRule方法用来给当前样式表插入新的样式规则.

语法

stylesheet.insertRule(rule, index)

参数

 

rule

一个包含了将要插入的规则的 DOMString。规则字符串必须包含的内容取决于它的类型:

index 可选
A positive integer less than or equal to stylesheet.cssRules.length, representing the newly inserted rule's position in CSSStyleSheet.cssRules. The default is 0. (In older implementations, this was required. See Browser compatibility for details.)

返回值

The newly inserted rule's index within the stylesheet's rule-list.

 

Restrictions

 

CSS has some intuitive and not-so-intuitive restrictions affecting where rules can be inserted. Violating them will likely raise a DOMException.

If index > CSSRuleList.length, the method aborts with an IndexSizeError. If rule cannot be inserted at index 0 due to some CSS constraint, the method aborts with a HierarchyRequestError. If more than one rule is given in the rule parameter, the method aborts with a SyntaxError. If trying to insert an @import at-rule after a style rule, the method aborts with a HierarchyRequestError. If rule is @namespace and the rule-list has more than just @import at-rules and/or @namespace at-rules, the method aborts with an InvalidStateError.

 

示例1

在样式表顶部插入新的规则

 myStyle.insertRule("#blanc { color: white }", 0); 

示例2

/**
 * Add a stylesheet rule to the document (may be better practice, however,
 *  to dynamically change classes, so style information can be kept in
 *  genuine styesheets (and avoid adding extra elements to the DOM))
 * Note that an array is needed for declarations and rules since ECMAScript does
 * not afford a predictable object iteration order and since CSS is 
 * order-dependent (i.e., it is cascading); those without need of
 * cascading rules could build a more accessor-friendly object-based API.
 * @param {Array} decls 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 (decls) {
    var style = document.createElement('style');
    document.getElementsByTagName('head')[0].appendChild(style);
    if (!window.createPopup) { /* For Safari */
       style.appendChild(document.createTextNode(''));
    }
    var s = document.styleSheets[document.styleSheets.length - 1];
    for (var i=0, dl = decls.length; i < dl; i++) {
        var j = 1, decl = decls[i], selector = decl[0], rulesStr = '';
        if (Object.prototype.toString.call(decl[1][0]) === '[object Array]') {
            decl = decl[1];
            j = 0;
        }
        for (var rl=decl.length; j < rl; j++) {
            var rule = decl[j];
            rulesStr += rule[0] + ':' + rule[1] + (rule[2] ? ' !important' : '') + ';\n';
        }

        if (s.insertRule) {
            s.insertRule(selector + '{' + rulesStr + '}', s.cssRules.length);
        }
        else { /* IE */
            s.addRule(selector, rulesStr, -1);
        }
    }
}

兼容垫片

The below polyfill will correct the input of the arguments of insertRule() to standardize them in Internet Explorer 5–8. It supplements insertRule() with a function that separates the selector from the rules before sending the arguments to the default native insertRule

(function(Sheet_proto){
  var originalInsertRule = Sheet_proto.insertRule;

  if (originalInsertRule.length === 2){ // 2 mandatory arguments: (selector, rules)
    Sheet_proto.insertRule = function(selectorAndRule){
      // First, separate the selector from the rule
      a: for (var i=0, Len=selectorAndRule.length, isEscaped=0, newCharCode=0; i !== Len; ++i) {
        newCharCode = selectorAndRule.charCodeAt(i);
        if (!isEscaped && (newCharCode === 123)) { // 123 = "{".charCodeAt(0)
          // Secondly, find the last closing bracket
          var openBracketPos = i, closeBracketPos = -1;

          for (; i !== Len; ++i) {
            newCharCode = selectorAndRule.charCodeAt(i);
            if (!isEscaped && (newCharCode === 125)) { // 125 = "}".charCodeAt(0)
              closeBracketPos = i;
            }
            isEscaped ^= newCharCode===92?1:isEscaped; // 92 = "\\".charCodeAt(0)
          }

          if (closeBracketPos === -1) break a; // No closing bracket was found!
            /*else*/ return originalInsertRule.call(
            this, // the sheet to be changed
            selectorAndRule.substring(0, openBracketPos), // The selector
            selectorAndRule.substring(closeBracketPos), // The rule
            arguments[3] // The insert index
          );
        }

        // Works by if the char code is a backslash, then isEscaped
        // gets flipped (XOR-ed by 1), and if it is not a backslash
        // then isEscaped gets XORed by itself, zeroing it
        isEscaped ^= newCharCode===92?1:isEscaped; // 92 = "\\".charCodeAt(0)
      }
      // Else, there is no unescaped bracket
      return originalInsertRule.call(this, selectorAndRule, "", arguments[2]);
    };
  }
})(CSSStyleSheet.prototype);

 

附注

对于普通样式规则来说,要插入的字符串应该包含选择器和样式声明.对于@规则来说,要插入的字符串应该包含@标识符和样式规则的内容.

相关链接

规范