找到一篇讲解offsetHeight, clientHeight, scrollHeight三者区别的文章,摘要出重点记录一下:

clientHeight:

returns the inner height of an element in pixels, including padding but not the horizontal scrollbar heightborder, 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

scrollHeightENTIRE content & padding (visible or not)
Height of all content + paddings, despite of height of the element.

clientHeightVISIBLE content & padding
Only visible height: content portion limited by explicitly defined height of the element.

offsetHeightVISIBLE content & padding + border + scrollbar
Height occupied by the element on document.

 

 

例子代码:

js

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');
}

css:
#MainDIV {
  border: 5px solid red;
}

html:

<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>

 

链接:

http://stackoverflow.com/questions/22675126/what-is-offsetheight-clientheight-scrollheight

具体例子代码:

http://jsfiddle.net/shibualexis/yVhgM/3/

 posted on 2017-04-21 16:44  a12345531  阅读(147)  评论(0)    收藏  举报