element.style display incorrect information
There is a simple html and javascript code:
<html>
<head>
<style>p { height: 100px;} </style>
<script>
window.onload = function(){
var p = document.getElementsByTagName("p")[0];
alert("actual height is " + p.style.height);
};
开发者_JS百科 </script>
<title>JavaScript Tests</title>
</head>
<body>
<p>
100px height p element
</p>
</body>
</html>
But when we run it actual height is equal to empty string.
Could you please explain why? Thanks.The style
property is different from the actual style in CSS: It looks for the style
attribute, so this:
<p style="height: 100px"></p>
<script>alert(document.getElementsByTagName("p")[0].style.height);</script>
will be "100px".
To get its actual height, use getComputedStyle()
.
<style> p { height: 100px; }</style>
<p></p>
<script>alert(getComputedStyle(document.getElementsByTagName("p")[0]).getPropertyValue("height"));</script>
The style
property refers to style attributes set explicitly on the element, not styles inherited from CSS declarations.
For example, try this:
<p style="height: 100px;">
Then you will see a value. See this document for an approach that will combine all of the various pieces of style information together to retrieve the actual composite style of an element.
精彩评论