在javascript dom中-元素的offsetHeight和clientHeight有什么区别?
返回对象可见区域的高度,以像素为单位。该值包含带有填充的高度,但不包括scrollBar,border和margin。
返回对象可见区域的高度,以像素为单位。该值包含带有边距,scrollBar和边框的高度,但不包括边距。
因此,不offsetHeight
包括滚动条和边框clientHeight
。
The answer from Oded is the theory. But the theory and the reality are not always the same, at least not for the <BODY> or the <HTML> elements which may be important for scrolling operations in javascript.
Microsoft has a nice image in the MSDN:
If you have a HTML page which shows a vertical scrollbar one would expect that either the <BODY> or the <HTML> element has a ScrollHeight geater than OffsetHeight as this image shows. This is true for all older versions of Internet Explorer.
But it is not true for Internet Explorer 11 and not for Firefox 36.
At least in these browsers OffsetHeight is nearly the same as ScrollHeight which is wrong.
And while OffsetHeight may be wrong, ClientHeight is always correct.
Try the following code on different browsers and you will see:
<!DOCTYPE html>
<html>
<body>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<script>
document.write("Body off: " + document.body.offsetHeight
+ "<br>Body cli: " + document.body.clientHeight
+ "<br>Html off: " + document.body.parentElement.offsetHeight
+ "<br>Html cli: " + document.body.parentElement.clientHeight);
</script>
</body>
</html>
尽管较旧的Internet Explorer可以正确显示:
Body off: 1197
Body cli: 1197
Html off: 878
Html cli: 874
Firefox和Internet Explorer 11的输出为:
Body off: 1260
Body cli: 1260
Html off: 1276 // this is completely wrong
Html cli: 889
这清楚地表明offsetHeight在这里是错误的。OffsetHeight和ClientHeight应该仅相差几个像素或相同。
请注意,对于不可见的元素,例如<FORM>,ClientHeight和OffsetHeight可能也有很大的不同,其中<set>其中OffsetHeight可能是FORM的实际大小,而ClientHeight可能是零。
文章标签:javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!