2011-02-22 49 views
4

我想抓住页面上的div的DISPLAY属性。如果它是通过内联样式属性设置的,我似乎只能抓住它。通过JS抓取style.display属性只有在设置了内联才有效?

如果我的JS是这样的:

alert(document.getElementById('myDiv').style.display); 

它会提醒 '块' 与此HTML:

<div id="myDiv" style="display: block;"></div> 

然而,如果我通过外部样式表进行设置:

#myID {display: block} 
我的HTML: 和我的HTML:

然后我的警报是一个空字符串。

这是为什么?

+0

你加载你的HTML之前运行您的JavaScript? – 2011-02-22 21:23:05

回答

9

这是CSS的“特征”。要实际获取样式,您需要使用window.getComputedStyle(大多数浏览器)或element.currentStyle(Internet Explorer)。

修复程序window.getComputedStyle可在以下位置找到IE:http://snipplr.com/view/13523/getcomputedstyle-for-ie/。此外,请参阅此页以获取更多信息:http://www.quirksmode.org/dom/getstyles.html#link7(对于跨浏览器getComputedStyle备选项,底部附近有一个脚本)。

这应该在所有的浏览器(基于上面怪异模式链接功能):

var elem = document.getElementById("myDiv"); 
if (elem.currentStyle) { 
    var displayStyle = elem.currentStyle.display; 
} else if (window.getComputedStyle) { 
    var displayStyle = window.getComputedStyle(elem, null).getPropertyValue("display"); 
} 
alert(displayStyle); 
+0

工作就像一个魅力!谢谢你的解释!我很惊讶,到目前为止我还没有遇到这个特殊的问题。 – 2011-02-22 21:39:55