返回当前样式的函数

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <style>
        #demo{
            100px;
            height:100px;
            background-color: pink;
            border:1px solid black;
            position:absolute;
            top:50px;
            left:100px;
            opacity:0.4;
        }
    </style>
</head>
<body>
<div id="demo"></div>
</body>
</html>
<script>
    var demo=document.getElementById("demo");
    function getStyle(obj,attr) //返回谁的,哪个属性
    {
        if(obj.currrentStyle)
        {
            return obj.currentStyle[attr];
        }
        else{
            return  window.getComputedStyle(obj,null)[attr]; //w3c浏览器
        }
    }

    console.log(getStyle(demo,"width"));
    console.log(getStyle(demo,"border"));
    console.log(getStyle(demo,"position"));
    console.log(getStyle(demo,"opacity"));
</script>

  

原文地址:https://www.cnblogs.com/shanlu0000/p/11260758.html