DIV CSS 佈局教程網

JS 取得 DIV 高度並動態重設寬高的實作
編輯:JavaScript綜合知識     

在做動態版面或互動元件時,經常需要讀取某個 DIV 目前的高度,再依需求重新設定它的寬與高。本文示範如何取得元素尺寸並動態調整,同時介紹幾種常見的取值屬性。

取得與設定尺寸的核心寫法

先封裝一個簡短的 $ 函式來取得元素,再透過 offsetWidth、offsetHeight 讀取尺寸,最後用 style 屬性重新設定寬高:

<script language="javascript">
  var $ = function(id) { return document.getElementById(id); };
  function clickDiv(){
    $('testid').offsetWidth; // 讀取寬度
    $('testid').offsetHeight; // 讀取高度
    document.all.testid.style.width = "1000px"; // 設定寬度
    document.all.testid.style.height = "500px"; // 設定高度
    $('testid').style.className = 'idtest';
  }
</script>

其他取得高度的屬性

除了 offsetHeight,依需求也可使用下列屬性取得高度:

scrollHeight:取得元素內容的完整滾動高度,即使內容超出可見區域也能抓到全部:

<script type="text/javascript">
  alert(document.getElementById("testid").scrollHeight + 'px');
</script>

clientHeight:取得元素的可見區域高度(含 padding,不含邊框與滾動條):

<script type="text/javascript">
  alert(document.getElementById("testid").clientHeight + 'px');
</script>

配合 CSS 的設定

元素的初始尺寸通常由 CSS 定義,JavaScript 再行覆寫:

<style type="text/css">
  #testid{
    height:50px;
    width:200px;
    background:#3300CC;
  }
  .idtest{
    height:80px;
    width:150px;
    background:#FFFFFF;
  }
</style>

觸發方式

透過按鈕的 onclick 呼叫函式即可觸發尺寸變更:

<body>
  <div id="testid"></div>
  <input type="button" value="點擊我" onclick="clickDiv();" />
</body>

屬性差異小提醒

實務上要留意幾個屬性的含義不同:offsetHeight 包含邊框與捲軸,clientHeight 只含 padding,scrollHeight 則代表內容的實際完整高度。選錯屬性可能導致取到非預期的數值。此外,直接設定 style.width/style.height 時務必帶上單位(如 px),否則在標準模式下可能不被正確解析。掌握這些細節,就能精準地讀取與控制元素尺寸。

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