Sometimes we need to use JS to dynamically generate CSS code in a style tag on a page, directly by creating a style element, then setting the CSS code inside the style element and inserting it into the head element. But there are some compatibility issues we need to solve. First of all, we just need to insert the CSS code into the style element as a text node in the Web browser, and in IE you have to use the stylesheet.csstext of the style element to solve it. It is also important to note that in some versions of IE, the number of style labels on a page is limited, if it exceeds the error, you need to consider this.
Put the code directly below to see the comment description.
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" border:0px; "/>
Function addcss (csstext) { var style = document.createelement (' style '), //creates a STYLE element head = document.head | | document.getelementsbytagname (' head ') [0]; //get head element style.type = ' Text/css '; //the Type property of the style element must be displayed here text/css, otherwise it will not work in IE if (style.stylesheet) { //ie var func = function () { try{ //prevent stylesheet errors in IE from exceeding the limit style.stylesheet.csstext = csstext; }catch (e) { } } //If the current stylesheet is not available, place the line in async if (style.styleSheet.disabled) { SetTimeout (func,10); }else{ func (); }  }ELSE{ //W3C        //W3C Browser as long as the creation of a text node inserted into the style element is OK var textnode = document.createtextnode (CssText); style.appendchild (Textnode); } head.appendchild (style); //inserts the created style element into the head }//use ADDCSS (' # Demo{ height: 30px; background: #f00;} ');
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" border:0px; "/>
Of course, this is only the most basic demonstration method, the actual application also needs to be perfected, for example, each generated CSS code is inserted into a STYLE element, so that in IE, there will be no more than the stylesheet limit of the number of errors.
Dynamically generate CSS code with JS