简体   繁体   中英

JavaScript .style.display?

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.net/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.net/bwzAN/7/

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

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" (ie the 'End Result') rather than your setup.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM