The CSS style can contain two elements in the HTML page. The & lt; link & gt; element is used to contain files from external sources, while the & lt; style & gt; element is used to specify the embedded style similar to the dynamic script, A dynamic style is a style that does not exist when the page is loaded. A dynamic style is dynamically added to the page after the page is loaded.
The typical Element:
Using DOM code, you can easily dynamically create this element:
The Code is as follows:
Var link = document. createElement ("link ");
Link. rel = "stylesheet ";
Link. type = "text/css ";
Link. href = "style.css? 1.1.23 ";
Var head = document. getElementsByTagName ("head") [0];
Head. appendChild (link );
The above code can run normally in all mainstream browsers. Note that Add elementInsteadTo ensure the behavior consistency in all browsers. The entire process can be represented by the following functions:
The Code is as follows:
Function loadStyles (url ){
Var link = document. createElement ("link ");
Link. rel = "stylesheet ";
Link. type = "text/css ";
Link. href = url;
Var head = document. getElementsByTagName ("head") [0];
Head. appendChild (link );
}
LoadStyles ("style.css? 1.1.23 ")
The process of loading external style files is asynchronous, that is, there is no fixed order between the process of loading styles and executing JavaScript code.
Another way to define a style is to use
The following DOM code should be valid according to the same logic:
The Code is as follows:
Var style = document. createElement ("style ");
Style. type = "text/css ";
Style. appendChild (document. createTextNode ("body {background-color: red ;}"));
Var head = document. getElementsByTagName ("head") [0];
Head. appendChild (style );
The above code can be run in Firefox, Safrai, Chrome, and Opera, and an error will be reported in IE. IE will