JavaScript的style属性可以获取html上标签的样式,但是不可以获取css里的样式我们怎么才能获取css里的样式?这时候就要用到JavaScript提供的currentStyle(ie)和getComputedStyle(火狐)来获取了!
<!DOCTYPE html>
<html>
<head>
<meta charset="gbk">
<title>获取行间样式</title>
<style>
#box{width: 200px;height: 200px;background: red;}
</style>
</head>
<body>
<div id="box"></div>
<script>
window.onload=function(){
var oBox=document.getElementById('box');
function getStyle(obj,attr) {
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
function css(obj,name,value){
if(arguments.length==2){
return getStyle(obj,name);
}else{
if(arguments.length==3){
return obj.style[name]=value;
}
}
}
alert(getStyle(oBox,'width'));
css(oBox,'background',"blue");
alert(css(oBox,'background'));
}
</script>
</body>
</html>