獲取及計算可滾動元素高度:區分clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop

獲取元素高度

一、基礎:理清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop區別

圖文可見:https://blog.csdn.net/qq_35430000/article/details/80277587

說的非常詳細,這邊列表總結如下:

名稱 範圍
clientHeight content高度(即包括上下padding)
offsetHeight content高度+上下border
scrollHeight 元素可滾動時,content實際高度;因此scrollHeight恆>=offsetHeight
offsetTop 在有滾動條時,滾動條向下滾動的距離也就是元素頂部被遮住部分的高度,無滾動條時爲0
scrollTop 當前元素頂部距離最近父元素頂部的距離,和有沒有滾動條無關。

如果要獲取margin值怎麼取?

// ele 表示指定元素dom節點
const marginBt = parseFloat(window.getComputedStyle(ele).marginBottom)

二、獲取滾動元素高度

(以vue爲例)

<div $ref="listheight">
......
</div>

const listheight = this.$refs.listheight.scrollHeight

三、手動計算指定子元素高度

let chil = this.$refs.listheight.children;
  // 可在for循環中獲取任意的子元素,此處爲所有元素的offsetHeight以及marginBottom值
  let calculateHeight = 0;
  for(var i = chil.length - 1; i >= 0; i--) {
    calculateHeight += chil[i].offsetHeight + parseFloat(window.getComputedStyle(chil[i]).marginBottom);
  }

參考:
https://blog.csdn.net/qq_35430000/article/details/80277587

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章