element.style显示不正确的信息

时间:2010-12-08 06:21:31

标签: javascript html css

有一个简单的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>

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

2 个答案:

答案 0 :(得分:2)

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

例如,试试这个:

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

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

答案 1 :(得分:2)

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>