DIV CSS 佈局教程網

jQuery 取得 DIV 的高度:height() 用法與常見陷阱
編輯:JQuery常見問題     

可以先看看效果:https:///keleyi/phtml/jquery/4.htm

語法只有一行:

$("#keleyi_com").height();

其中 keleyi_com 是 DIV 的 id。

完整示例代碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jquery 獲取 DIV的高度(height) -</title>
<script type="text/javascript" src="https:///keleyi/pmedia/jquery-1.8.3.min.js"></script>
</head>
<body>
<div id="keleyi_com" style="width:800px;border:1px solid silver;height:300px">本DIV的id為keleyi_com;</div>
<script type="text/javascript">
$(document).ready(function () {
  alert("id為keleyi_com的高度(height)為:" + $("#keleyi_com").height());
})
</script>
</body>
</html>

height() 到底算什麼

height() 回傳的是內容高度,不包含 padding、border 與 margin。對應的一組方法:

  • .height():內容高度。
  • .innerHeight():內容 + padding。
  • .outerHeight():內容 + padding + border。
  • .outerHeight(true):再加上 margin。

寬度部分完全對稱:width()、innerWidth()、outerWidth()。做彈窗置中或遮罩鋪滿時,通常要用 outerHeight() 才不會因為忽略邊框而產生位移。

幾個容易踩到的坑

  • 隱藏元素取不到值。display:none 的元素 height() 回傳 0,若必須取得,可先 visibility:hidden; position:absolute 暫時顯示出來量測。
  • 圖片尚未載入。圖片高度由內容決定時,要在 .load() 或 $(window).load() 之後才量得到正確值。
  • 回傳的是數字,沒有 "px"。拼接字串時要自己補單位,例如 el.style.height = h + 'px'。
  • 設定高度時用 $("#id").height(300) 即可,jQuery 會自動補上 px。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved