[英]JavaScript .style.display?
I want to get display attribute from an HTML element. 我想从HTML元素中获取display属性。 When I write inline CSS, it works, but if I use a class it doesn't. 当我编写内联CSS时,它可以工作,但是如果我使用类,它就不会。
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/ 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/ http://jsfiddle.net/bwzAN/7/
Why? 为什么? Is it possible to make the second case behave like the first? 是否有可能使第二种情况像第一种情况一样? How can I fix it? 我该如何解决?
Take a look at getComputedStyle()/getPropertyValue(). 看看getComputedStyle()/ getPropertyValue()。 The property .style.display will only return the inline style property as you already mentioned. 属性.style.display将仅返回您已提到的内联样式属性。
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/ 我已经创建了一个JSFiddle(你的非工作原文的一个分支)来帮助你: http : //jsfiddle.net/Jamesking56/qTKYK/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.