javascript 操作 css Rule

 //add   addCssRule('.bcd',{'color':'red','font-weight':'bold','font-size':'12px'},document.styleSheets[1]);
function addCssRule(selector,styles,styleSheet,index){
var sheets = styleSheet instanceof Array ? styleSheet : [styleSheet],
style = '',
declaration = '';
for(var pro in styles){
if(styles.hasOwnProperty(pro)){
declaration += (pro + ':' + styles[pro] + ';');
}
}
style = selector + '{' + declaration + '}';
for(var i = 0,j = sheets.length; i < j;i++){
if(sheets[i].insertRule){
index = index >= 0 ? index : sheets[i]['cssRules'].length;
sheets[i].insertRule(style,index);
}else if(sheets[i].addRule){ //IE
index = index >= 0 ? index : -1; //-1为末尾
sheets[i].addRule(selector,declaration,index);
}
}
} //modify editCssRule('.abc',{'font-weight':'bold','font-size':'14px'},document.styleSheets[1]);
function editCssRule(selector,styles,styleSheet){
var sheets = styleSheet instanceof Array ? styleSheet : [styleSheet];
selector = selector.toUpperCase(); // ie9以下标签选择器默认是大写 这里统一下
//对大小写敏感的selector 会有问题
for(var i = 0,j = sheets.length; i < j;i++){
var rules = sheets[i]['cssRules'] || sheets[i]['rules']; //ie为 rules
if(!rules){ continue;}
for(var m = 0,n = rules.length;m < n;m++){
if(rules[m]['selectorText'].toUpperCase() == selector){
for(var pro in styles){
if(styles.hasOwnProperty(pro)){
rules[m].style[cssCamilize(pro)] = styles[pro];
}
}
}
}
}
} //del delCssRule('.bcd',document.styleSheets[1]);
function delCssRule(selector,styleSheet,index){
var sheets = styleSheet instanceof Array ? styleSheet : [styleSheet];
selector = selector.toUpperCase();
for(var i = 0,j = sheets.length; i < j;i++){
var rules = sheets[i]['cssRules'] || sheets[i]['rules']; //ie为 rules
if(index >=0 && index < rules.length){
sheets[i].deleteRule ? sheets[i].deleteRule(index) : sheets[i].removeRule(index);
}else if(selector){
for(var m = 0,n = rules.length;m < n;m++){
if(rules[m]['selectorText'].toUpperCase() == selector){
sheets[i].deleteRule ? sheets[i].deleteRule(m) : sheets[i].removeRule(m);; //可能存在多个一样的selector 全部删除
}
}
}else{
return false;
}
}
}; function cssCamilize(str){
return str.replace(/-(\w)/g,function($1,$2){
return $2.toUpperCase();
});
};
//参考:http://www.cnblogs.com/2050/p/4029656.html
function addCSS(cssText){
var style = document.createElement('style'), //创建一个style元素
head = document.head || document.getElementsByTagName('head')[0]; //获取head元素
style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用
if(style.styleSheet){ //IE
var func = function(){
try{ //防止IE中stylesheet数量超过限制而发生错误
style.styleSheet.cssText = cssText;
}catch(e){ }
}
//如果当前styleSheet还不能用,则放到异步中则行
if(style.styleSheet.disabled){
setTimeout(func,10);
}else{
func();
}
}else{ //w3c
//w3c浏览器中只要创建文本节点插入到style元素中就行了
var textNode = document.createTextNode(cssText);
style.appendChild(textNode);
}
head.appendChild(style); //把创建的style元素插入到head中
}
上一篇:Spring源码阅读 之 配置的读取,解析


下一篇:《剑指offer》第二十二题(链表中倒数第k个结点)