弄清楚煩人的clientHeight與clientTop、scrollHeight與scrollTop、offsetHeight與offsetTop與JQuery中的innerHeight()與...

clientHeight與clientTop

  • clientHeight

包括 padding 但不包括 border水平滾動條、margin的元素的高度。對于行內元素這個屬性一直是0。單位為px,只讀元素。

client-MDN
  • clientTop

元素頂部邊框的寬度單位為px,可以理解為border-top。如沒有設置 border-top的值,則 element.clientTop 的值為 0

client-MDN

注意如下情況:
??

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>clientHeight</title>
  <style>
    div#ct {
      width: 250px;
      height: 250px;
      border: 15px solid blue;
      text-align: center;
      background-color: pink;
      margin: 100px;
      padding: 20px;
      overflow: scroll;
    }
    div#item {
      color: red;
      background-color: #666;
      width: 400px;
      height: 1000px;
    }
  </style>
</head>
<body>
 <div id="ct">
   <div id="item">Helo World!</div>
</div>
</body>
</html>
clientHeight

clientHeight 字面意思即為自身的高度, 在上例 容器內部的子元素的高度 高于父容器,因為 overflow: scroll;所以出現滾動條。但元素本身的clientHeight 是不受這些因素影響的(這一點容易點混淆)。所以 div#ct.cilentHeight 與 div#item.clientHeight還是開始設置樣式是的值。

Element.getBoundingClientRect()

返回元素的大小及其『相對于視口左上角(其中width height不是相對于左上角)』的位置(且結果會保留小數比clientHeight精確)。

Element.getBoundingClientRect()

element.getBoundingClientRect()包括 top right bottom left height width

  • top right bottom left: 相對于視口左上角的原點位置,不包括 margin 的值,但是會包括滾動條
  • height width: height 矩形盒子的高度。 width矩形盒子的寬度, 且存在width = right - left height = bottom - top

scrolltHeight與scrollTop

  • scrollHeight

等于在沒有垂直滾動條 的情況下,為所需要填充內容視圖的最小值,包括padding(無論可見還是不可見)。 其元素的本身(而不是它的父容器)的 clientHeight 等于 scrollHeight

scrollHeight
  • scrollTop

元素的頂部到視口可見內容的頂部 的距離的度量,前提是這個元素的本身有垂直滾動條,否則 scrollTop的值為 0

scrollTop

注: 如果垂直方向的scrolllBar存在,且當前元素滾動到底:

element.scrollHeight - element.scrollTop === element.clientHeight
// true

offsetHeight與offsetTop

  • offsetHeight(高度偏移)

元素CSS高度的衡量標準,包括 border padding 還包括 水平方向上的 scrollBar。不包括偽元素的高度

offsetHeight = content + padding + border + 水平方向的scrollBar

offsetHeight

  • offsetTop(頂部偏移)

當前元素相對于其 當前最接近的父輩元素的頂部內邊距的距離。

也就是當前元素的 border-top(不包括border的值) 到 最接近的 父元素的margin-top邊緣的距離

offsetTop

JQuery中的 innerHeight與outerHeight

詳情如圖所示

JQuery中的 innerHeight與outerHeight

參考:

MDN

nsIDOMClientRect-MDN

stack overflow-What is offsetHeight, clientHeight, scrollHeight?

medium-Difference between offsetHeight, clientHeight and scrollHeight

stack overflow- What is difference between width, innerWidth and outerWidth, height, innerHeight and outerHeight in jQuery - Stack Overflow


版權聲明:本文為博主原創文章,未經博主許可不得轉載

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容