File Name StyleSheet. js
Copy codeThe Code is as follows:
// The CssRule class is returned by the StyleSheet. getRule method and is not directly created.
Function CssRule (rule ){
This. rule = rule;
This. style = rule. style;
This. selectorText = rule. selectorText;
This. index = null;
}
Function StyleSheet (){
Var head = document. getElementsByTagName ("head") [0];
// Create a style by creating a tag
/*
Document. createStyleSheet is not used here, because in FF
The document. createStyleSheet method fails if no CSS file is imported.
*/
Var style = document. createElement ("style ");
Style. type = "text/css ";
Head. appendChild (style );
This. CatchStyle (document. styleSheets. length-1 );
}
StyleSheet. prototype = {
// You can directly capture existing styles.
CatchStyle: function (index ){
This. style = document. styleSheets [index];
If (navigator. userAgent. indexOf ("MSIE") <0) {// non-IE browser patch
This. style. addRule = function (selector, style ){
Var index = this.css Rules. length;
This. insertRule (selector + "{" + style + "}", index );
};
This. style. removeRule = function (index ){
This. deleteRule (index );
};
}
},
// Add a style
AddRule: function (selector, style ){
This. style. addRule (selector, style );
},
// Delete a style
RemoveRule: function (index ){
This. style. removeRule (index );
},
// Obtain all styles
GetRules: function (){
If (this. style. rules) {// IE
Return this. style. rules;
}
Return this.style.css Rules; // non-IE
},
// Obtain the style through the selector
GetRule: function (selector ){
Var rules = this. getRules ();
For (var I = 0; I <rules. length; I ++ ){
Var r = rules [I];
If (r. selectorText = selector ){
Var rule = new CssRule (r );
Rule. index = I;
Return rule;
}
}
Return null;
}
};
Call sample code
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script src = "StyleSheet. js" type = "text/javascript"> </script>
<Script language = "javascript" type = "text/javascript"> <! --
Var ss = new StyleSheet ();
Window. onload = function (){
Ss. AddRule (". test", "color: # FF0000; background-color: # F0F0F0; font-size: 12px; border: solid 1px # A0A0A0 ;");
}
Function Set (){
Var r = ss. getRule (". test ");
Var slt = document. getElementById ("tbSelector"). value;
Var v = document. getElementById ("tbValue"). value;
Var style = r. style;
Style [slt] = v;
}
// --> </Script>
</Head>
<Body>
Style <input id = "tbSelector" type = "text" value = "width"/>
Value <input id = "tbValue" type = "text" value = "300px"/>
<Input type = "button" value = "Set" onclick = "Set ()"/>
<Div class = "test"> a </div>
<Div class = "test"> B </div>
<Div class = "test"> c </div>
<Div class = "test"> d </div>
<Div class = "test"> e </div>
</Body>
</Html>