我想从HTML元素中获取显示属性。当我编写内联CSS时,它可以工作,但是如果我使用一个类,它就不能工作。
这是可行的:
<p id="p1" style="display:none;">This is some text.</p>
<script>alert(document.getElementById("p1").style.display);</script>http://jsfiddle.net/bwzAN/2/
这不起作用:
<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/
为什么?有没有可能让第二种情况像第一种情况一样呢?我怎么才能修复它?
发布于 2012-09-12 04:12:53
用getComputedStyle() - 尝试一下
$(document).ready(function(){
var elem = document.getElementById("p1");
var st = window.getComputedStyle(elem, null).getPropertyValue("display");
alert( st );
});发布于 2012-09-12 04:13:11
看看getComputedStyle()/getPropertyValue()。正如您已经提到的,属性.style.display将只返回内联样式属性。
var yourDisplay = window.getComputedStyle(document.getElementById('yourID'), null).getPropertyValue('display');发布于 2012-09-12 04:15:48
你需要得到“计算风格”(即“最终结果”),而不是你的设置。
我已经创建了一个JSFiddle (您的非工作原件的分支)来帮助您:http://jsfiddle.net/Jamesking56/qTKYK/2/
https://stackoverflow.com/questions/12377141
复制相似问题