平時很少需要動態插入 style 規則,但有一次為了臨時解決頁面樣式問題——需要批量更新很多引用同一公共 JS 的頁面樣式——直接在公共 JS 裡向 style sheet 插入新的 style rule 就顯得格外方便。下面看看具體做法。
復制代碼 代碼如下:
/**
* 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);
}
}
}
調用示例:
復制代碼 代碼如下:
addStylesheetRules([["div.content", ["color": "#000"], ["border-width","1px"], ["border-style", "solid"]]])
執行後,當前 document 的 head 標簽內會多出一個 style:
復制代碼 代碼如下:
<style>
div.content{color:#000;border:1px solid}
</style>
由於每次調用都會插入一個新的 style,所以最好只調用一次、一次插入多條 rule:
復制代碼 代碼如下:
addStylesheetRules(
[selector, [attr, value], …],
[selector, [attr, value], …]
);
標準方法:stylesheet.insertRule(rule, index)
rule:被插入的規則,如 div.content{color:#000}
index:插入順序,從 0 開始,先後順序會影響樣式(層疊)。Firefox、Chrome、Opera、Safari,以及 IE9 起也支持此方法。
IE 的方法:stylesheet.addRule(selector, styleDef [, positionIndex])
selector:如 div.content
styleDef:如 color:#000
positionIndex:默認 -1,插入到末尾。IE、Safari、Chrome 支持此方法。