FileName Stylesheet.js
Copy Code code as follows:
The Cssrule class is returned by the Stylesheet.getrule method and is not created 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 with a new label
/*
It's not document.createstylesheet to do here, because under FF
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 capture the existing style directly
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);
};
}
},
New Style
Addrule:function (selector, style) {
This.style.addRule (selector, style);
},
Delete a 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 by 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;
}
};
Calling sample Code
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<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>
<body>
Style <input id= "Tbselector" type= "text" value= "width"/>
Value <input id= "Tbvalue" type= "text" value= "300px"/>
<input type= "button" value= "setting" 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>