2007-08-21

javascript获取网页元素的最终样式

关键字: javascript css
      今天遇到个问题,用js获取网页元素的样式,如果直接用 document.getElementById("idname").style 获取的话,只能获取该元素的专有样式,即在该元素上直接用style=“”指定的样式,而无法获取由class设置的和从上级元素继承来的样式,也就是浏览器生成dom后最终的样式,所以很头痛。网上搜索了一下,找到一个办法。
     
 
  1. <html>  
  2.   <head>  
  3.   <style type="text/css">  
  4.   div.special{  
  5.    background-color:red;  
  6.    height:50px;  
  7.    width:50px;  
  8.    margin:10px;  
  9.   }  
  10.   </style>  
  11.   <script language="JavaScript">  
  12.   function getBackgroundColor()  
  13.   {  
  14.    var oDiv=document.getElementById("div1");  
  15.    alert(oDiv.currentStyle.backgroundColor||document.defaultView.getComputedStyle(oDiv,null).backgroundColor);  
  16.   }  
  17.   </script>  
  18.   </head>  
  19.   <body>  
  20.   <div id="div1" class="special"></div>  
  21.   <input type="button" value="Get Background Color" onclick="getBackgroundColor()">  
  22.     </input>  
  23.   </body>  
  24.   </html>  

      注意:oDiv.currentStyle.backgroundColor是IE使用的方法,document.defaultView.getComputedStyle(oDiv,null).backgroundColor是DOM使用的方法。

       内容来源:http://blog.tianya.cn/blogger/post_show.asp?BlogID=666817&PostID=7224874&idWriter=0&Key=0
评论
damoo 2007-08-21
不错,顶一个
发表评论

您还没有登录,请登录后发表评论

jolestar
搜索本博客
存档
最新评论