元素的style属性时常被用于获取元素样式,但很多时候它是不奏效的。看下面的代码:
<html> <body> <style> #ex2 {height:100px;width:100px;background:blue;} </style> <div style="height:100px;width:100px;background:green;" id='ex1'></div> <div id='ex2'></div> <script> var elem1 = document.getElementById('ex1'); alert(elem1.style.width); var elem2 = document.getElementById('ex2'); alert(elem2.style.width); </script> </body> </html>我们发现,elem1的值是可以取到的(100px),但elem2则是空。这是因为,style属性只能获取内联样式。那么对于非内联样式我们应该如何取得其值呢?微软和W3C都提供了解决方案。
微软方案
使用currentStyle属性,它的工作方式很像style属性,但你不能通过它设置样式。
例如:
var x = document.getElementById(‘test’); alert(x.currentStyle.color);W3C方案
使用window.getComputedStyle()方法,这个方法的使用略复杂。
例如:
var x = document.getElementById(‘test’); alert(window.getComputedStyle(x, null).color);整合两种解决方案,我们给出函数
function getRealStyle(elem, styleName){ var realStyle = null; //微软 if (elem.currentStyle){ realStyle = elem.currentStyle[styleName]; } //W3C else if (window.getComputedStyle){ realStyle = window.getComputedStyle(elem, null)[styleName]; } return realStyle; }使用这个函数,我们可以得到elem2的正确值100px。
代码如下:
var elem2 = document.getElementById('ex2'); alert(getRealStyle(elem2, 'width'));
注:
getComputedStyle()总是返回一个像素值(**px),即使我们在css中定义是样式是11%或是50em。
参考:《ppk谈javascript》第9章 CSS修改 A style属性