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" character 02.16.style.css Text = "background: # ff0000; border: 1px # dfdfsolid ;";
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: the following code references a piece of code of "situ zhengmei)
VaraddSheet = function (){
Vardoc, cssCode;
If (arguments. length = 1 ){
Doc = document;
CssCode = arguments [0]
} Elseif (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.
Vart = 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.
VarheadElement = doc. getElementsByTagName ("head") [0];
VarstyleElements = headElement. getElementsByTagName ("style ");
If (styleElements. length = 0) {// if the style element does not exist, create
If (doc. createStyleSheet) {// ie
Doc. createStyleSheet ();
} Else {
VartempStyleElement = doc. createElement ('style'); // w3c
TempStyleElement. setAttribute ("type", "text/css ");
HeadElement. appendChild (tempStyleElement );
}
}
VarstyleElement = styleElements [0];
Varmedia = styleElement. getAttribute ("media ");
If (media! = Null &&! /Screen/. test (media. toLowerCase ())){
StyleElement. setAttribute ("media", "screen ");
}
If (styleElement. styleSheet) {// ie
StyleElement.styleSheet.css Text + = cssCode;
} Elseif (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.
FunctionaddStyle (stylePath ){
Varcontainer = document. getElementsByTagName ("head") [0];
VaraddStyle = document. createElement ("link ");
AddStyle. rel = "stylesheet ";
AddStyle. type = "text/css ";
AddStyle. media = "screen ";
AddStyle. href = stylePath;
Container. appendChild (addStyle );
}
AddStyle ('css/add.css ');