代码之家  ›  专栏  ›  技术社区  ›  Jichao

如何检索DOM元素的display属性?

  •  12
  • Jichao  · 技术社区  · 14 年前
    <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 设置,第三个 警觉的 没有人

    但为什么呢?我怎样才能取回 显示 属性正确吗?

    4 回复  |  直到 14 年前
        1
  •  34
  •   YektaDev    4 年前

    这个 .style.* 属性直接映射到 style 属性 ,而不是应用的样式。为了你想要的 getComputedStyle .

    我会认真考虑换衣服 .className 把表现和逻辑完全分开。

        2
  •  7
  •   Tim Down    14 年前

    window.getComputedStyle() 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);
    }
    
        3
  •  3
  •   Å ime Vidas Zim84    14 年前

    我建议使用JavaScript库来获得计算风格。例如,使用jQuery可以使用css()方法检索computed样式。。。

    $("#a").css("display");
    

    css()方法是一种跨浏览器的解决方案,因为它在内部使用style对象、getComputedStyle方法和currentStyle对象。

        4
  •  0
  •   mplungjan Gvidas    8 年前

    如果可以使用jQuery,那么有一个方法 .is

    $('someSelector').is(':visible') ...