Home >Web Front-end >JS Tutorial >Dynamic style class encapsulation JS code_javascript skills

Dynamic style class encapsulation JS code_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:47:141257browse

File name StyleSheet.js

Copy code The code is as follows:

// The CssRule class is provided by StyleSheet. The getRule method returns and does not create directly
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 new style by creating a new tag
/*
Document.createStyleSheet is not used here because under 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 = {
//Can directly capture existing Style
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.cssRules.length;
this.insertRule(selector "{" style "}", index);
};
this.style.removeRule = function(index) {
this.deleteRule(index);
} ;
}
},
//Add style
AddRule: function(selector, style) {
this.style.addRule(selector, style);
},
//Remove style
RemoveRule: function(index) {
this.style.removeRule(index);
},
//Get all styles
getRules: function() {
if (this.style.rules) { //IE
return this.style.rules;
}
return this.style.cssRules; //Non-IE
},
//Get 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 the sample code
Copy code The code is as follows:

" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




< script language="javascript" type="text/javascript">


Style
Value

a

b

c

d

< ;div class="test">e



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Tips on using parseInt in javascript_Basic knowledgeNext article:Tips on using parseInt in javascript_Basic knowledge

Related articles

See more