如何检索 DOM 元素的显示属性? [英] How to retrieve the display property of a DOM element?
问题描述
<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>
第一个和第二个 alert
只显示一个空字符串,我认为应该是 none
和 block
.然而,在本质上display
设置之后,第三个alert
终于alert none
.
The first and the second alert
display nothing other than a empty string, which I thought should be none
and block
.
However after the intensionally display
setting, the third alert
finally alert none
.
但是为什么?如何正确检索 display
属性?
But Why? How could I retrieve the display
property correctly?
谢谢.
推荐答案
.style.*
属性直接映射到 style
属性,而不是应用的样式.为此,您需要 getComputedStyle.
The .style.*
properties map directly onto the style
attribute, not to the applied style. For that you want getComputedStyle.
我会认真考虑切换 .className
并将演示文稿与逻辑完全分开.
I'd give serious consideration to toggling .className
and separating the presentation from the logic entirely.
这篇关于如何检索 DOM 元素的显示属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!