问题描述
我正在尝试获取页面上div的DISPLAY属性.我似乎只能抓住它,如果它是通过内联样式属性设置的.
I'm trying to grab the DISPLAY property of a div on a page. I can only seem to grab it if it was set via an inline style attribute.
如果我的JS是这样的:
If my JS is this:
alert(document.getElementById('myDiv').style.display);
它将使用以下HTML警报阻止":
It will alert 'block' with this HTML:
<div id="myDiv" style="display: block;"></div>
但是,如果我通过外部样式表进行设置:
However, if I set it via an external style sheet:
#myID {display: block}
和我的HTML:
<div id="myDiv"></div>
然后我的警报是一个空字符串.
then my alert is an empty string.
这是为什么?
推荐答案
这是CSS的功能".要真正获得样式,您需要使用 window.getComputedStyle (大多数浏览器)或 element.currentStyle (Internet Explorer).
This is a "feature" of CSS. To actually get the style, you need to use window.getComputedStyle (most browsers) or element.currentStyle (Internet Explorer).
可以在以下位置找到实现 window.getComputedStyle IE的修复程序: http://snipplr.com/view/13523/getcomputedstyle-for-ie/.此外,请参阅此页面以获取更多信息: http://www.quirksmode.org/dom/getstyles.html#link7 (底部附近有一个脚本,用于跨浏览器的getComputedStyle替代方法.)
A fix to implement window.getComputedStyle IE can be found at: http://snipplr.com/view/13523/getcomputedstyle-for-ie/. Additionally, see this page for more info: http://www.quirksmode.org/dom/getstyles.html#link7 (there is a script near the bottom for a cross-browser getComputedStyle alternative).
这应该在所有浏览器中都可以使用(基于上面QuirksMode链接的功能):
This should work in all browsers (based on function from QuirksMode link above):
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);
这篇关于通过JS抓取style.display属性仅在设置内联时有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!