The dynamic style class encapsulates JS Code and dynamically changes the style. File Name StyleSheet. js
The 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
The Code is as follows:
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>