javascript 如何检索 DOM 元素的显示属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3778335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve the display property of a DOM element?
提问by Jichao
<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
<a href="http://www.google.com" id="a">google</a>
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>
The first and the second alertdisplay nothing other than a empty string, which I thought should be noneand block.
However after the intensionally displaysetting, the third alertfinally alert none.
第一个和第二个只alert显示一个空字符串,我认为应该是noneand block。然而经过刻意的display设定,第三个人alert终于警觉起来none。
But Why? How could I retrieve the displayproperty correctly?
但为什么?我怎样才能display正确检索财产?
Thanks.
谢谢。
回答by Quentin
The .style.*properties map directly onto the styleattribute, not to the applied style. For that you want getComputedStyle.
的.style.*属性直接映射到style属性,而不是所施加的样式。为此,您需要getComputedStyle。
I'd give serious consideration to toggling .classNameand separating the presentation from the logic entirely.
我会认真考虑完全切换.className和分离演示文稿与逻辑。
回答by Tim Down
You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle()whereas the nearest equivalent in IE is the element's currentStyleproperty:
您需要元素的显示属性的计算值。您可以按如下方式获取。请注意,大多数浏览器都支持,window.getComputedStyle()而 IE 中最接近的等价物是元素的currentStyle属性:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}
回答by ?ime Vidas
I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
我建议使用 JavaScript 库来获取计算样式。例如,使用 jQuery,您可以使用 css() 方法检索计算样式...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.
css() 方法是一种跨浏览器解决方案,因为它在内部使用样式对象以及 getComputedStyle 方法和 currentStyle 对象。
回答by ?ime Vidas
If you can use jQuery, there is a method called .is
如果你可以使用jQuery,有一个方法叫做 .is
To check if something isn't displayed, I'd do ... $('someSelector').is(':visible')...
要检查是否未显示某些内容,我会做$('someSelector').is(':visible')......
This would return false if display attribute is set to None.
如果显示属性设置为无,这将返回 false。

