最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

动态样式类封装JS代码_javascript技巧

来源:动视网 责编:小采 时间:2020-11-27 20:44:08
文档

动态样式类封装JS代码_javascript技巧

动态样式类封装JS代码_javascript技巧:文件名StyleSheet.js 代码如下:// CssRule类由StyleSheet.getRule方法返回,不直接创建 function CssRule(rule) { this.rule = rule; this.style = rule.style; this.selectorText = rule.selectorText;
推荐度:
导读动态样式类封装JS代码_javascript技巧:文件名StyleSheet.js 代码如下:// CssRule类由StyleSheet.getRule方法返回,不直接创建 function CssRule(rule) { this.rule = rule; this.style = rule.style; this.selectorText = rule.selectorText;


文件名StyleSheet.js
代码如下:
// CssRule类由StyleSheet.getRule方法返回,不直接创建
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];
//通过新建标签来创建新样式
/*
在此不用document.createStyleSheet来完成,是因为在FF下
如果未导入任何CSS文件的情况下document.createStyleSheet方法失败
*/
var style = 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) {
var index = 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
return this.style.rules;
}
return this.style.cssRules; //非IE
},
//通过选择器,取得样式
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;
}
};

调用示例代码
代码如下:
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




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;
}
// -->


样式


a
b
c
d
e


文档

动态样式类封装JS代码_javascript技巧

动态样式类封装JS代码_javascript技巧:文件名StyleSheet.js 代码如下:// CssRule类由StyleSheet.getRule方法返回,不直接创建 function CssRule(rule) { this.rule = rule; this.style = rule.style; this.selectorText = rule.selectorText;
推荐度:
标签: 技巧 动态 js
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top