You can click the following link to view the original implementation and discussion. This version mainly fixes bugs and caches some objects to improve efficiency:
Dynamic add style sheet rules and dynamic add style rules
// 2011.3.6 by situ zhengmei; (function (Win, DOM) {This. DOM = This. dom | {}; var reg_media =/screen | all/I, reg_opacity =/opacity: \ s * (\ D? \. \ D +)/g Dom. addsheet = function (CSS, appendto) {var self = arguments. callee, style, El = appendto | Dom. Body if (! Self. style) {var styles = Dom. getelementsbytagname ("style"), I = 0, media while (style = styles [I ++]) {media = style. getattribute ("Media"); If (Media = NULL | reg_media.test (media) {self. style = style; break; }}if (! Self. Style) {style = Dom. createelement ('style'); El. appendchild (style); self. Style = style ;}} if (! -[1,] & el. filters) {// IE6-8 CSS = CSS. replace (reg_opacity, function ($, $1) {$1 = parsefloat ($1) * 100; if ($1 <0 | $1> 100) Return ""; return "filter: alpha (opacity =" + $1 + ");"}) ;}css + = "\ n"; // Add a line break at the end, it is easy to view in firebug. If (style. stylesheet) {// ie style.stylesheet.css text + = CSS; // Add a new internal style} else if (win. components) {style. innerhtml + = CSS; // Firefox supports adding style sheet strings directly to innerhtml} else {style. appendchild (Dom. createtextnode (CSS)} finally vertex (this,this.doc ument)
Usage:
dom.addSheet("body{background:#666;color:#fff;}")
var addCSS = (function(){var style = document.createElement('style');style.type = 'text/css';var root = document.getElementsByTagName('head')[0] || document.body;root.appendChild(style);return function(css){style.appendChild(document.createTextNode(css+'\n'));};})();