复制代码 代码如下:
// 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) 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 var r = rules[i];
if (r.selectortext == selector) {
var rule = new cssrule(r);
rule.index = i;
return rule;
}
}
return null;
}
};
调用示例代码
复制代码 代码如下:
br>http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>
样式
值
a
b
c
d
e