There are many ways to dynamically create style nodes, but most of them are limited to external CSS files. I spent two hours creating a style node dynamically using the string generated by the program.
Static external CSS File Syntax:
@ Import url(style.css );
Dynamic external CSS file loading methods are as follows:
First:
VaR style = Document. createelement ('link ');
Style. href = 'style.css ';
Style. rel = 'stylesheet ';
Style. type = 'text/CSS ';
Document. getelementsbytagname ('head'). Item (0). appendchild (style );
The second is simple:
Document.createstylesheet(style.css );
The dynamic style node uses the string generated by the Program:
VaR style = Document. createelement ('style ');
Style. type = 'text/CSS ';
Style. innerhtml = "body {background-color: Blue ;}";
Document. getelementsbytagname ('head'). Item (0). appendchild (style );
Unfortunately, the above Code succeeded in FF, but IE does not support it. Get the code from the foreigner Forum:
VaR sheet = Document. createstylesheet ();
Sheet. addrule ('body', 'background-color: red ');
But it is very troublesome. We need to take the string apart and write it a little longer.
Search for the code on a blog that does not know the language of the country:
Document. createstylesheet ("javascript: 'body {background-color: Blue ;'");
Successful, this person is really amazing, but the problem comes out. The URL can contain a maximum of 255 characters, but it will not work if it is longer. After the sxpcrazy prompt, change it:
Window. Style = "body {background-color: Blue ;";
Document. createstylesheet ("javascript: Style ");
Perfect solution !! Code:
<HTML>
<Head>
<SCRIPT>
Function blue (){
If (document. All ){
Window. Style = "body {background-color: Blue ;";
Document. createstylesheet ("javascript: Style ");
} Else {
VaR style = Document. createelement ('style ');
Style. type = 'text/CSS ';
Style. innerhtml = "body {background-color: Blue }";
Document. getelementsbytagname ('head'). Item (0). appendchild (style );
}
}
</SCRIPT>
</Head>
<Body>
<Input type = "button" value = "blue" onclick = "blue ();"/>
</Body>
</Html>