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