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

 今天遇到个问题,用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值