您的位置:首页 > Web前端 > CSS

JS获取CSS属性值

2016-10-24 15:05 465 查看
[html] view
plain copy

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  

<html>  

 <head>  

  <meta http-equiv="content-type" content="text/html; charset=utf-8">  

  <title> JS获取CSS属性 </title>  

  <style type="text/css">  

    #f{background-color:#FF0000;}  

  </style>  

 </head>  

  

 <body>  

  <div id="f" style="width:200px; height:200px;"></div>  

  

  <script type="text/javascript">  

    var o = document.getElementById('f');  

    document.write(o.style.width + '<br>'); // 200px  

    document.write(o.style.backgroundColor + '<br>'); // 空白  

  

    function getDefaultStyle(obj,attribute){  

        return obj.style?obj.style[attribute] : document.defaultView.getComputedStyle(obj,false)[attribute];     

    }  

    document.write(getDefaultStyle(o, 'width') + '<br>'); // 200px  

    document.write(getDefaultStyle(o, 'backgroundColor')); // #FF0000  

  </script>  

   

 </body>  

  

</html>  

JS獲取CSS屬性方法:

[javascript] view
plain copy

function getDefaultStyle(obj,attribute){  

    return obj.currentStyle?obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj,false)[attribute];     

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: