想解释一下offsetHeight
、clientHeight
和scrollHeight
或offsetWidth
、有什么区别clientWidth
和 scrollWidth
?
在客户端工作之前,必须知道这种差异。否则他们一半的生命将花在修复 UI 上。
Fiddle , 或内联:
function whatis(propType) {
var mainDiv = document.getElementById("MainDIV");
if (window.sampleDiv == null) {
var div = document.createElement("div");
window.sampleDiv = div;
}
div = window.sampleDiv;
var propTypeWidth = propType.toLowerCase() + "Width";
var propTypeHeight = propType + "Height";
var computedStyle = window.getComputedStyle(mainDiv, null);
var borderLeftWidth = computedStyle.getPropertyValue("border-left-width");
var borderTopWidth = computedStyle.getPropertyValue("border-top-width");
div.style.position = "absolute";
div.style.left = mainDiv.offsetLeft + Math.round(parseFloat((propType == "client") ? borderLeftWidth : 0)) + "px";
div.style.top = mainDiv.offsetTop + Math.round(parseFloat((propType == "client") ? borderTopWidth : 0)) + "px";
div.style.height = mainDiv[propTypeHeight] + "px";
div.style.lineHeight = mainDiv[propTypeHeight] + "px";
div.style.width = mainDiv[propTypeWidth] + "px";
div.style.textAlign = "center";
div.innerHTML = propTypeWidth + " X " + propTypeHeight + "( " +
mainDiv[propTypeWidth] + " x " + mainDiv[propTypeHeight] + " )";
div.style.background = "rgba(0,0,255,0.5)";
document.body.appendChild(div);
}
document.getElementById("offset").onclick = function() {
whatis('offset');
}
document.getElementById("client").onclick = function() {
whatis('client');
}
document.getElementById("scroll").onclick = function() {
whatis('scroll');
}
#MainDIV {
border: 5px solid red;
}
<button id="offset">offsetHeight & offsetWidth</button>
<button id="client">clientHeight & clientWidth</button>
<button id="scroll">scrollHeight & scrollWidth</button>
<div id="MainDIV" style="margin:auto; height:200px; width:400px; overflow:auto;">
<div style="height:400px; width:500px; overflow:hidden;">
</div>
</div>
最佳答案
要知道区别,您必须了解 box model ,但基本上:
clientHeight :
returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin
offsetHeight :
is a measurement which includes the element borders, the element vertical padding, the element horizontal scrollbar (if present, if rendered) and the element CSS height.
scrollHeight :
is a measurement of the height of an element's content including content not visible on the screen due to overflow
我会让事情变得更容易:
考虑:
<element>
<!-- *content*: child nodes: --> | content
A child node as text node | of
<div id="another_child_node"></div> | the
... and I am the 4th child node | element
</element>
scrollHeight:整个内容和填充(可见或不可见)
所有内容的高度+填充,尽管元素的高度。
clientHeight:可见的内容和填充
仅可见高度:内容部分受明确定义的元素高度限制。
offsetHeight:VISIBLE content & padding
+边框+滚动条
元素在文档中所占的高度。
关于javascript - 什么是 offsetHeight、clientHeight、scrollHeight?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675126/