首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >什么是offsetHeight、clientHeight、scrollHeight?

什么是offsetHeight、clientHeight、scrollHeight?
EN

Stack Overflow用户
提问于 2014-03-27 07:21:03
回答 3查看 173.9K关注 0票数 297

我想解释一下offsetHeightclientHeightscrollHeightoffsetWidthclientWidthscrollWidth之间的区别

在客户端工作之前,必须了解这一区别。否则,他们的一半生命将花费在修复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>

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22675126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档