Not written for a long timeArticleToday's idea of dynamically adding CSS files
-
- Method 1: Document. getelementbyid ("Elementid"). Style. Background="# Ff0000";
In this way, inline is used to insert CSS. The priority is high. This vulnerability may cause poor page reflux performance and cannot be added to multiple styles.
Method 2:
Document. getelementsbytagname ("A")[0].Style.css text= "Background: # ff0000; Border: 1px # dfdfdf solid;";
Compared with the first method, this method can be used to set multiple styles at a time, but it is still inline, leading to page backflow and performance consumption caused by multiple inserts.
- The third method is to directly write in the style label. This method takes into account the compatibility of different browsers. (Declaration: below Code Reference a piece of code of "situ zhengmei) VaR addsheet = function () {
VaR doc, csscode;
If (arguments. Length = 1 ){
Doc = document;
Csscode = arguments [0]
} Else if (arguments. Length = 2) {
Doc = arguments [0];
Csscode = arguments [1];
} Else {
Alert ("addsheet function can accept up to two parameters! ");
}
If (! + "\ V1 ") { // Added the automatic conversion transparency function. You only need to enter the W3C transparent style, which will be automatically converted to the IE transparent filter.
VaR T = csscode. Match (/opacity : (\ D? \. \ D +) ; /);
If (T! = NULL ){
Csscode = csscode. Replace (T [0], "Filter : Alpha (opacity = "+ parsefloat (T [1]) * 100 + ")")
}
}
Csscode = csscode + "\ n"; // Add line breaks at the end to facilitate viewing in firebug.
VaR headelement = Doc. getelementsbytagname ("head") [0];
VaR styleelements = headelement. getelementsbytagname ("style ");
If (styleelements. Length = 0) { // Create a style if the style element does not exist
If (Doc. createstylesheet) {// IE
Doc. createstylesheet ();
} Else {
VaR tempstyleelement = Doc. createelement ('style'); // W3C
Tempstyleelement. setattribute ("type", "text/CSS ");
Headelement. appendchild (tempstyleelement );
}
}
VaR styleelement = styleelements [0];
VaR media = styleelement. getattribute ("Media ");
If (media! = NULL &&! /Screen/. Test (media. tolowercase ())) {
Styleelement. setattribute ("Media", "screen ");
}
If (styleelement. stylesheet) { // IE
Styleelement.stylesheet.css text + = csscode;
} Else if (Doc. getboxobjectfor) {
Styleelement. innerhtml + = csscode; // Firefox supports adding style sheet strings directly in innerhtml
} Else {
Styleelement. appendchild (Doc. createtextnode (csscode ))
}
}
4. Load CSS files dynamically, which is simple.
Function addstyle (stylepath) {
VaR Container = Document. getelementsbytagname ("head") [0];
VaR addstyle = Document. createelement ("Link ");
Addstyle. rel = "stylesheet ";
Addstyle. type = "text/CSS ";
Addstyle. Media = "screen ";
Addstyle. href = stylepath;
Container. appendchild (addstyle );
}
Addstyle ('css/add.css ');