Many martyrs have summarized the dynamic creation of large sections of inline CSS styles on pages and possible problems, such asArticle: Weird ie-2. I will not go into details here. I just want to forget it.
In fact, there are still questions: whether stylesheetnode. innerhtml = STR is supported by browsers other than IE
Directly go to the demo andCode:
. Red {color: red ;}
<P class = "Red Green"> This is the most elegant text I have ever seen. click the button below to turn green! </P> <button onclick = "addstyle () "> click </button> <Li> safari 6 </LI> </OL>
Function $ (ID) {return document. getelementbyid (ID);} function addstyle () {var S = document. createelement ('style'); S. setattribute ('type', 'text/CSS '); var STR = '. green {color: green;} '; If (S. stylesheet) {s.stylesheet.css text = STR;} else {S. innerhtml = STR;} document. getelementsbytagname ('head') [0]. appendchild (s );}
A strange problem has not been further investigated:
VaR S = document. createstylesheet (); S. setattribute ('type', 'text/CSS '); // The error is returned because there is no setattribute s.stylesheet.css text = 'P {color: green;}'; // The error is reported because the stylesheet attribute does not exist.