Dynamic Loading refers to loading external CSS files and dynamically creating style sheet elements. The methods I have summarized here may not be complete, but try to provide some of the methods used in the use process to everyone.
First, how to dynamically load an external CSS file: (the file name is style.css)
The least technical method:
Document. Write ("");
@ Import(style.css)
This method can only be used in external CSS files or style nodes. It cannot be regarded as dynamic. Both ff and IE are feasible.
Use the document. createstylesheet () method
This method is ie only, and the parameter can pass the value in a style sheet, for example, body {Background: bluegion is the URL of an external CSS file, such as document.createstylesheet(style.css). The URL address is relative to the current page.
Dynamically create link nodes
Function loadcss (cssurl ){
? VaR link = Document. createelement ("Link ");
? Link. rel = "stylesheet ";
? Link. type = "text/CSS ";
? Link. href = "cssurl ";
? Document. getelementsbytagname ("body"). Item (0). appednchild (Link );
}
This method can be used in ff and IE. Of course, the same idea can also be used to create a style node, and then the XMLHttpRequest method can be used to load content in cssurl, and set the innerhtml of the created style node to the responsetext of XMLHttpRequest. However, because I think this is the least economical and unreasonable method, I will not talk about it here.
Update a link node
The idea is the same as above, but this method replaces an existing link label and can be used to change the theme of a website. Code As follows:
Function changetheme (cssurl ){
? VaR theme = Document. getelementbyname ("theme"); // assume that a node with the ID of theme exists.
? Theme. href = cssurl;
}
I have tested this method and it is feasible in ff and IE.
Dynamically create style elements
What should I do if I want to add the following CSS elements to a webpage?
. Focus {
? Color: red;
? Font-style: bold;
}
Of course, I can create a style node and put the above content in innerhtml. Is there any other way? So far, I do not know the method above except for a feasible method in ff and IE. However, in IE, we can do this:
VaR sheet = Document. createstylesheet ();
Sheet. addrule (". Focus", "color: red; font-style: bold ;");
Article If anything is wrong, please let me know.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/cxc3214/archive/2007/11/01/1861379.aspx