2010-12-08 102 views
3

有一个简单的HTML和JavaScript代码:element.style显示不正确的信息

<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

style属性是在CSS的实际风格不同:它看起来为style属性,所以这样的:

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

将是“100像素”。请使用getComputedStyle()

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

请注意,getComputedStyle()在所有流行的IE版本中都得不到很好的支持。 – cdhowie 2010-12-08 06:49:21

2

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

例如,试试这个:

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

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