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