js计算机样式window.getComputedStyle(ele,null)与

一、getComputedStyle兼容IE8以上,范户籍的计算样式的值都是绝对值,没有相对单位(如:10em; 它打印出来是160px)

window.getComputedStyle(div,null)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>window.getComputedStyle(div,null)</title>
    <style type="text/css">
        *{margin:0;padding:0}
    </style>
</head>
<body>
<div style=" 100px; height: 100px; background: red;"></div>
<script type="text/javascript">
    var div = document.getElementsByTagName('div')[0]
console.log(div.currentStyle.width)//IE独有属性
</script> <strong>【代码说明】</strong> <div><strong>getComputedStyle</strong>获取计算机样式</div> </body> </html>

效果图:

二、ele.currentStyle  

ele.currentStyle    是IE独有的属性;返回的计算样式的值不是经过转换的绝对值

封装getStyle,如下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>window.getComputedStyle(div,null)</title>
    <style type="text/css">
        *{margin:0;padding:0}
    </style>
</head>
<body>
<div style=" 100px; height: 100px; background: red;"></div>
<script type="text/javascript">
    var div = document.getElementsByTagName('div')[0]
    //封装
    function getStyle(elem,prop){
        if(window.getComputedStyle){        //如果它存在的话(兼容谷歌)
            return window.getComputedStyle(elem,null)[prop];//prop作为参数字符串传进来,所有得中括号
        }else{
            return elem.currentStyle[prop];   //兼容IE
        }
    }
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/huanghuali/p/8564488.html