通过JS获取style.display属性只能在设置内联时使用?

时间:2011-02-22 20:56:38

标签: javascript css

我正在尝试在页面上抓取div的DISPLAY属性。如果它是通过内联样式属性设置的,我似乎只能抓住它。

如果我的JS是这样的:

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

它将使用此HTML警告“阻止”:

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

但是,如果我通过外部样式表设置它:

#myID {display: block}

和我的HTML:

<div id="myDiv"></div>

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

这是为什么?

1 个答案:

答案 0 :(得分:11)

这是CSS的“功能”。要真正获得样式,您需要使用 window.getComputedStyle (大多数浏览器)或 element.currentStyle (Internet Explorer)。

可以在http://snipplr.com/view/13523/getcomputedstyle-for-ie/找到实现 window.getComputedStyle IE的修复程序。另外,请参阅此页面以获取更多信息:http://www.quirksmode.org/dom/getstyles.html#link7(底部附近有一个脚本,用于跨浏览器的getComputedStyle替代方案)。

这适用于所有浏览器(基于上面QuirksMode链接的功能):

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);