一:内联样式
页面上的每一个元素,DOM都引入了一个style对象,对于元素的每个CSS样式,style都包含了一个相对应的属性,通过style.属性名可以来访问和操作对应
的CSS样式。
需要注意的地方:style的属性名和CSS样式的属性名有一定区别,对于单个单词的属性名,二者完全相同,对于多个单词的CSS样式,CSS采取的是用连接
线,而style属性去掉了连接线,采取的是类似于编程语言的驼峰命名法,例如font-family(CSS样式)——fontFamily(DOM中style属性名).
此外,style属性只对内联属性起作用,对于CSS中style块或者外联样式表,只能采取下面的方式访问。
示例:
<body>
<input type="button" value="测试" style="background-color: #90ee90;" id="btn1" οnclick="func1()">
<script>
function func1(){
var btn=document.getElementById("btn1");
alert(btn.style.backgroundColor);
btn.style.backgroundColor="gray";
}
</script>
</body>
二:操作style块及外部样式表
1:获取所有的样式的集合,var rules= document.styleSheets.cssRules||document.styleSheets[0].rules;注意:因为浏览器的差异,前者为标准的DOM集合,后者
为IE浏览器自定义的集合。
2:获取单个样式:rules[i].属性名,i为style中CSS规则的位置,按从上至下的顺序,从0开始。
示例:
<head>
<title></title>
<meta http-equiv="content-type" content="text/html charset=utf-8"/>
<style>
#div1{
border: 1px solid blue;
width: 200px;
height: 40px;
}
#div2{
border: 1px solid green;
width: 300px;
height: 60px;
}
</style>
</head>
<body>
<div id="div2">
<input type="button" value="测试样式表" style="background-color: #90ee90;" id="btn2" οnclick="func2()">
</div>
<script>
function func2(){
var rules= document.styleSheets.cssRules||document.styleSheets[0].rules;
rules[1].style.background="yellow";
}
</script>
</body>