【问题标题】:element.style display incorrect informationelement.style 显示不正确的信息
【发布时间】:2010-12-08 14:24:13
【问题描述】:

有一个简单的html和javascript代码:

<html>
    <head>
        <style>p { height: 100px;} </style>
        <script>
            window.onload = function(){
                var p = document.getElementsByTagName("p")[0];
                alert("actual height is " + p.style.height);
            };
        </script>
        <title>JavaScript Tests</title>
    </head>
    <body>
        <p>
            100px height p element
        </p>
    </body>
</html>

但是当我们运行它时,实际高度等于空字符串。
你能解释一下为什么吗?
谢谢。

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    style 属性与 CSS 中的实际样式不同:它查找 style 属性,因此:

    <p style="height: 100px"></p>
    <script>alert(document.getElementsByTagName("p")[0].style.height);</script>
    

    将是“100px”。

    要获得它的实际高度,请使用getComputedStyle()

    <style> p { height: 100px; }</style>
    <p></p>
    <script>alert(getComputedStyle(document.getElementsByTagName("p")[0]).getPropertyValue("height"));</script>
    

    【讨论】:

    • 请注意,getComputedStyle() 并非在所有流行的 IE 版本中都得到很好的支持。
    • 确实如此。您可以在 IE 中使用elem.currentStyle.height
    【解决方案2】:

    style 属性是指在元素上显式设置的样式属性,不是从 CSS 声明继承的样式。

    例如,试试这个:

    <p style="height: 100px;">
    

    然后你会看到一个值。请参阅 this document 了解将所有各种样式信息组合在一起以检索元素的实际复合样式的方法。

    【讨论】:

      猜你喜欢
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多