Grabbing style.display property via JS only works when set inline?
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.
If my JS is this:
alert(document.getElementById('myDiv开发者_Python百科').style.display);
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}
and my HTML:
<div id="myDiv"></div>
then my alert is an empty string.
Why is this?
This is a "feature" of CSS. To actually get the style, you need to use window.getComputedStyle (most browsers) or element.currentStyle (Internet Explorer).
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).
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);
精彩评论