DIV CSS 佈局教程網

JavaScript 取得元素實際高度:getBoundingClientRect 用法解析
編輯:關於JavaScript     

用 CSS 寫死高度是一回事,想知道元素「實際渲染出來有多高」又是另一回事。特別是當高度用了百分比、內距(padding)又有值時,clientHeight、offsetHeight 各自算法不同,很容易搞混。

這裡示範一種兼容性不錯的做法:透過 getBoundingClientRect() 取得元素在視窗中的矩形,再從中算出高度。

取得高度的函式

function getHeight(){
  var height = 0;
  var div = document.getElementById("date").getBoundingClientRect();
  if(div.height){
    height = div.height;
  }else{
    height = div.bottom - div.top;
  }
  return height;
}

邏輯很單純:先看矩形物件有沒有 height 屬性,有就直接用;沒有就退回用 bottom 減 top 自己算。這道防線是為了應付舊版瀏覽器——早期實作回傳的矩形只有 top、bottom、left、right 四個值,height 與 width 是後來才補上的。

完整範例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一個 JavaScript 實例-獲取元素當前高度</title>
<style>
  #date{ width:90%; height:25%; padding:10px; background: red; }
</style>
<script>
window.onload = function(){
  var height = getHeight();
  console.log(height);
}
function getHeight(){
  var height = 0;
  var div = document.getElementById("date").getBoundingClientRect();
  if(div.height){
    height = div.height;
  }else{
    height = div.bottom - div.top;
  }
  return height;
}
</script>
</head>
<body>
<div style="width:1000px;height:800px;">
  <div id="date"></div>
</div>
</body>
</html>

範例中外層容器固定 800px 高,#date 設為 25%,因此高度會落在 200px 上下;再加上左右各 10px 的 padding,實際佔用的空間會比 200px 多一些。

幾種高度取值方式的差異

  • offsetHeight:包含內容、padding 與 border,是整數,會四捨五入。
  • clientHeight:包含內容與 padding,不含 border 與 scrollbar。
  • scrollHeight:元素內部實際內容的高度,可能大於 clientHeight(有溢出時)。
  • getBoundingClientRect().height:包含 padding 與 border,且會反映 CSS transform 縮放後的視覺尺寸,回傳浮點數。

正因為有 transform 縮放這個特性,做縮放動畫或需要精準像素對位時,getBoundingClientRect 往往比 offsetHeight 可靠。反過來,如果只是要判斷「內容有沒有溢出」,scrollHeight 才是對的工具。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved