小编典典

如何获取DOM元素的display属性?

css

<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显示的内容只不过是一个空字符串,我认为应该是noneand
block。但是,经过精心display设置之后,第三个alert终于警报了none

但为什么?我如何才能display正确检索该属性?

谢谢。


阅读 1808

收藏
2020-05-16

共1个答案

小编典典

.style.*属性直接映射到style 属性,而不是所施加的样式。为此,您需要getComputedStyle。

我会认真考虑切换.className演示文稿并将其与逻辑完全分开。

2020-05-16