获取元素计算后的css样式封装

时间:2021-12-22 08:06:30

获取元素计算后的css样式封装:

    function getCss(obj,attribute) {
if(obj.currentStyle) {
return obj.currentStyle[attribute];}else {
return window.getComputedStyle(obj,null)[attribute];}
}

案例:

<!DOCTYLE html>
<html>
<head>
<meta charset="uft-8" />
<style>
#box {width:100px; height: 100px; background:#dfd; position:absolute; left:100px; top:100px;}
</style>
</head>
<body>
<button id="btn1">200</button>
<button id="btn2">600</button>
<div id="box"></div>
</body>
</html>
<script>
function getCss(obj,attribute) {
if(obj.currentStyle) {
return obj.currentStyle[attribute];}else {
return window.getComputedStyle(obj,null)[attribute];}
}
console.log(getCss(box,'zIndex'));
</script>