新しい CSS 規則を現在のスタイルシートに挿入しますが、いくつかの制限があります。→MS
メモ: insertRule() は CSSStyleSheet の排他的なメソッドですが、実際には規則を CSSStyleSheet.cssRules、内部的には CSSRuleList(en-US)に挿入します。
| rule | 挿入される規則が入った DOMString です。どのような規則を挿入するかは、種類に依存します。
|
|---|---|
| index | stylesheet.cssRules.length 以下の正の数で、CSSStyleSheet.cssRules の中で新しく挿入される規則の位置を示します。
既定値は 0 です。(古い実装では、これは必須でした。詳しくはブラウザーの対応を参照してください。) |
戻り値: スタイルシートの規則リスト内の、新たに挿入された規則のインデックスです。
CSS スタイルシート規則のリストには、規則がどのようにどこへ挿入されるかに影響する、いくつかの直感的な、またはそれほど直感的でない 制限 があります。これらに違反すると、DOMException のようなエラーを引き起こす原因になるでしょう。
// myStyle の先頭に新しい規則を挿入
myStyle.insertRule("#blanc { color: white }", 0);
/**
* 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) {
var styleEl = document.createElement('style');
// Append <style> element to <head>
document.head.appendChild(styleEl);
// Grab style element's sheet
var styleSheet = styleEl.sheet;
for (var i = 0; i < rules.length; i++) {
var j = 1,
rule = rules[i],
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];
j = 0;
}
for (var pl = rule.length; j < pl; j++) {
var prop = rule[j];
propStr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';
}
// Insert CSS Rule
styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
}
}
¶省く
| 表示内容: |
| 表示内容: |