JS获取CSS属性值

<!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.currentStyle?obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj,false)[attribute];   
    }
    document.write(getDefaultStyle(o, 'width') + '<br>'); // 200px
    document.write(getDefaultStyle(o, 'backgroundColor')); // #FF0000
  </script>
 
 </body>

</html>

 

posted @ 2015-08-31 16:03  狄枫  阅读(762)  评论(0编辑  收藏  举报