最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Grabbing style.display property via JS only works when set inline? - Stack Overflow

programmeradmin5浏览0评论

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').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?

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').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?

Share Improve this question asked Feb 22, 2011 at 20:56 DA.DA. 40.7k51 gold badges158 silver badges217 bronze badges 1
  • Are you running your javascript before loading your HTML? – Ryan Kinal Commented Feb 22, 2011 at 21:23
Add a ment  | 

1 Answer 1

Reset to default 13

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./view/13523/getputedstyle-for-ie/. Additionally, see this page for more info: http://www.quirksmode/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);
发布评论

评论列表(0)

  1. 暂无评论