zl程序教程

您现在的位置是:首页 >  后端

当前栏目

动态样式类封装JS代码

JS封装代码 动态 样式
2023-06-13 09:14:12 时间
文件名StyleSheet.js
复制代码代码如下:

//CssRule类由StyleSheet.getRule方法返回,不直接创建
functionCssRule(rule){
this.rule=rule;
this.style=rule.style;
this.selectorText=rule.selectorText;
this.index=null;
}
functionStyleSheet(){
varhead=document.getElementsByTagName("head")[0];
//通过新建标签来创建新样式
/*
在此不用document.createStyleSheet来完成,是因为在FF下
如果未导入任何CSS文件的情况下document.createStyleSheet方法失败
*/
varstyle=document.createElement("style");
style.type="text/css";
head.appendChild(style);
this.CatchStyle(document.styleSheets.length-1);
}
StyleSheet.prototype={
//可直接捕获现有Style
CatchStyle:function(index){
this.style=document.styleSheets[index];
if(navigator.userAgent.indexOf("MSIE")<0){//非IE浏览器补丁
this.style.addRule=function(selector,style){
varindex=this.cssRules.length;
this.insertRule(selector+"{"+style+"}",index);
};
this.style.removeRule=function(index){
this.deleteRule(index);
};
}
},
//新增样式
AddRule:function(selector,style){
this.style.addRule(selector,style);
},
//删除样式
RemoveRule:function(index){
this.style.removeRule(index);
},
//取得所有样式
getRules:function(){
if(this.style.rules){//IE
returnthis.style.rules;
}
returnthis.style.cssRules;//非IE
},
//通过选择器,取得样式
getRule:function(selector){
varrules=this.getRules();
for(vari=0;i<rules.length;i++){
varr=rules[i];
if(r.selectorText==selector){
varrule=newCssRule(r);
rule.index=i;
returnrule;
}
}
returnnull;
}
};

调用示例代码
复制代码代码如下:

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<scriptsrc="StyleSheet.js"type="text/javascript"></script>
<scriptlanguage="javascript"type="text/javascript"><!--
varss=newStyleSheet();
window.onload=function(){
ss.AddRule(".test","color:#FF0000;background-color:#F0F0F0;font-size:12px;border:solid1px#A0A0A0;");
}
functionSet(){
varr=ss.getRule(".test");
varslt=document.getElementById("tbSelector").value;
varv=document.getElementById("tbValue").value;
varstyle=r.style;
style[slt]=v;
}
//--></script>
</head>
<body>
样式<inputid="tbSelector"type="text"value="width"/>
值<inputid="tbValue"type="text"value="300px"/>
<inputtype="button"value="设置"onclick="Set()"/>
<divclass="test">a</div>
<divclass="test">b</div>
<divclass="test">c</div>
<divclass="test">d</div>
<divclass="test">e</div>
</body>
</html>