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

JavaScript .style.display? - Stack Overflow

programmeradmin0浏览0评论

I want to get display attribute from an HTML element. When I write inline CSS, it works, but if I use a class it doesn't.

This works:

<p id="p1" style="display:none;">This is some text.</p>​
<script>alert(document.getElementById("p1").style.display);</script>

/

This does not work:

<style>.deneme{ display: none; }​</style>
<p id="p1" class="deneme">This is some text.</p>​
<script>alert(document.getElementById("p1").style.display);</script>

/

Why? Is it possible to make the second case behave like the first? How can I fix it?

I want to get display attribute from an HTML element. When I write inline CSS, it works, but if I use a class it doesn't.

This works:

<p id="p1" style="display:none;">This is some text.</p>​
<script>alert(document.getElementById("p1").style.display);</script>

http://jsfiddle/bwzAN/2/

This does not work:

<style>.deneme{ display: none; }​</style>
<p id="p1" class="deneme">This is some text.</p>​
<script>alert(document.getElementById("p1").style.display);</script>

http://jsfiddle/bwzAN/7/

Why? Is it possible to make the second case behave like the first? How can I fix it?

Share Improve this question edited Sep 11, 2012 at 20:14 bfavaretto 71.9k18 gold badges117 silver badges159 bronze badges asked Sep 11, 2012 at 20:08 AliRıza AdıyahşiAliRıza Adıyahşi 15.9k24 gold badges117 silver badges197 bronze badges 4
  • Please update your question with the relevant information from your links should they ever go dead. – Naftali Commented Sep 11, 2012 at 20:13
  • You already got correct answers mentioning getComputedStyle. However, this won't work in older Internet Explorer versions. For this browser, you can use element.currentStyle.display. – duri Commented Sep 11, 2012 at 20:14
  • @Neal I had done that for the OP, but my edit was overwritten... Edited again. – bfavaretto Commented Sep 11, 2012 at 20:15
  • @bfavaretto ahhh interesting. – Naftali Commented Sep 11, 2012 at 20:15
Add a ment  | 

3 Answers 3

Reset to default 6

Try it with getComputedStyle() - DEMO

$(document).ready(function(){
    var elem = document.getElementById("p1");
    var st   = window.getComputedStyle(elem, null).getPropertyValue("display");

    alert( st );
});

Take a look at getComputedStyle()/getPropertyValue(). The property .style.display will only return the inline style property as you already mentioned.

var yourDisplay = window.getComputedStyle(document.getElementById('yourID'), null).getPropertyValue('display');

You need to get the "Computed Style" (i.e. the 'End Result') rather than your setup.

I've created a JSFiddle (A fork of your non-working original) to help you: http://jsfiddle/Jamesking56/qTKYK/2/

发布评论

评论列表(0)

  1. 暂无评论