<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#btn1{
background-color: burlywood;
}
#box1{
border: 1px solid black;
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload=function(){
var box1=document.getElementById("box1");
var btn1=document.getElementById("btn1");
btn1.onclick=function(){
alert(box1.style.backgroundColor);
//用style只能能读取内联样式
}
var btn2=document.getElementById("btn2");
btn2.onclick=function(){
alert(box1.currentStyle.backgroundColor);
//用currentStyle读取元素当前显示的样式,如果当前元素不设置样式,则获取他的默认值
//currentStyle属性这个只有IE浏览器支持,其他浏览器不支持
}
var btn3=document.getElementById("btn3");
var box=getComputedStyle(box1,null );
//getComputedStyle方法可以获取元素当前的样式,该方法会返回一个对象,对象中封装了这个元素的样式
//该方法不支持IE8及以下的浏览器
//如果没有设置样式的宽度,则会设置他的实际宽度而不是默认宽度了
btn3.onclick=function(){
alert(box.backgroundColor);
alert(typeof box.backgroundColor);
alert(getStyle(box1,"backgroundColor"));
//调用自己定义的getStyle()函数
getStyle(box1,"backgroundColor");
}
/*
* 通过currentStyle和getComputedStyle读取的样式都是只读的
* 不能修改,如果要修改,必须通过style属性
/
/
* 定义一个函数,用来获取元素当前的样式
* 参数:
* obj 要获取样式的元素
* name 要获取的样式名
*/
function getStyle(obj , name){/*getComputedStyle前面不加window就是一个变量 *在全局中没有这个变量,所以运行在IE浏览器时会报错 * 但是加了window就表示时window的一个属性 * 在IE浏览器中是没有这个属性的,只会返回undefied * */
if(window.getComputedStyle){
//正常浏览器的方法
return getComputedStyle(obj,null)[name];
}
else{
//IE8浏览器的方法
return obj.currentStyle[name];//}
}
}
}
</script>
</head>
<body>
<button id="btn1">点我一下获取内联样式</button>
<button id="btn2">点我一下获取元素当前的样式</button>
<button id="btn3">点我一下获取样式表中的样式样式</button>
<button onclick="wo()">我是自己定义的函数</button>
<br />
<div id="box1" style="background-color: green;">123</div>
</body>
</html>