DOM操作表格及样式4

<link href="basic4.css">
<style>
</style>


window.onload=function(){
//更加简便的获取sheet的方法
//document.styleSheets得到的是StyleSheetList集合
var sheet=document.styleSheets[0]; //这个属性,所有浏览器都兼容的 得到的是link里的样式,不是style里的
//alert(sheet.disabled=true); //禁用
//alert(sheet.href); //获取url
//alert(sheet.title);

//下面是重点
alert(sheet.cssRules); //CSSRuleList,是样式规则集合
//样式的规则就是,一群样式的集合表示一个规则
alert(sheet.cssRules[0]); //CSSStyleRule,得到第一个规则
alert(sheet.cssRules[0].cssText); //得到第一个规则的CSS文本 #box {font-size:20px;color:red;background:
#ccc;}
alert(sheet.cssRules[0].selectorText); //得到第一个规则的选择符 #box
sheet.deleteRule(0);//删除第一条规则
sheet.insertRule('body {background-color: red}',0); //添加一条规则在第一个位置上

PS:IE对应的另一种方式:
//sheet.cssRules //非IE获取Rules
//sheet.rules; //代替cssRules的IE版本

sheet.deleteRule(0);//非IE删除第一条规则
sheet.removeRule(0); //代替deleteRule的IE版本

sheet.insertRule('body {background-color: red}',0); //非IE添加一条规则在第一个位置上
sheet.addRule('body','background-color:red',0); //代替insertRule的IE版本

//跨浏览器兼容获取rules
var rules=sheet.cssRules||sheet.rules;

//跨浏览器兼容删除第一条规则
deleteRule(sheet,0);


//跨浏览器兼容添加第一条规则
insertRule(sheet,'body','background-color:red',0);
}
//跨浏览器兼容添加第一条规则
function insertRule(sheet,selectorText,cssText,position){
if(sheet.insertRule){
sheet.insertRule(selectorText+'{'+cssText+'}',position);
}else if(sheet.addRule){
sheet.addRule(selectorText,cssText,position);
}
}

//跨浏览器兼容删除第一条规则
function deleteRule(sheet,position){
if(sheet.deleteRule){
sheet.deleteRule(position);
}else if(sheet.removeRule){
sheet.removeRule(position);
}
}

3个规则:
#box {
font-size:20px;
color:red;
background: #ccc;
}
#pox {
}
.c {
}


----------------------------------------------------
window.onload=function(){
var sheet=document.styleSheets[0];
var rules=sheet.cssRules||sheet.rules;
var rule1=rules[0];
alert(rule1.cssText);
alert(rule1.selectorText);
alert(rule1.style.color);
rule1.style.color='blue'

var box=document.getElementById('box');
alert(box.style.color); //获取不到.css文件里的样式
}

总结:三种操作CSS的方法,第一种style行内,可读可写;第二种行内、内联和链接,使用getComputedStyle或
currentStyle,可读不可写;第三种cssRules或rules,内联和链接,可读可写。

posted @ 2017-08-22 11:48  耿鑫  阅读(167)  评论(0编辑  收藏  举报