返回当前样式的函数

<!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{
            width: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>

  

posted @ 2019-07-28 20:26  shanlu  阅读(168)  评论(0编辑  收藏  举报