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