<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>获取样式的封装函数</title>
<style type="text/css">
#box{
width: 200px;
height: 100px;
background: #A6F188;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
var div = document.getElementById("box");
//获取某个元素的css样式,浏览器兼容
function getStyle(domobj,attr){
if(window.getComputedStyle){
return getComputedStyle(domobj,null)[attr];//现代浏览器
//return getComputedStyle(domobj,null).attr;
}else{
return domobj.currentStyle(attr);//支持IE低版本
}
}
var w = getStyle(div,"width");
var h = getStyle(div,"height");
var color = getStyle(div,"background");
console.log(w,h,color);
</script>
</body>
</html>