DIV CSS 佈局教程網

JavaScript 取得與設定 div 寬高,相容各種瀏覽器
編輯:關於JavaScript     

用 JavaScript 讀取或設定 div 的寬高,看似簡單,但要在不同瀏覽器下都能正確運作,仍有幾個細節需要注意。以下示範相容 FF 與 IE 的寫法。

HTML 結構

<div id="div1" style="height:300px;width:200px;">https://www.itdos.com</div>
<div id="div2" style="height:30px;width:20px;">https://www.itdos.com</div>

取得 div1 的寬高

alert(document.getElementById("div1").offsetHeight); //兼容 FF、IE 等
alert(document.getElementById("div1").offsetWidth); //兼容 FF、IE 等

將 div1 的寬高設為 div2 的寬高

document.getElementById("div1").style.height=document.getElementById("div2").offsetHeight; //僅 IE
document.getElementById("div1").style.height=document.getElementById("div2").offsetHeight+ "px"; //兼容 FF、IE 等
document.getElementById("div1").style.width=document.getElementById("div2").offsetWidth; //僅 IE
document.getElementById("div1").style.width=document.getElementById("div2").offsetWidth+ "px"; //兼容 FF、IE 等

關鍵差異在於:設定寬高時,IE 可以直接接受數值,但 Firefox 等標準瀏覽器必須明確加上 "px" 單位。因此加上 "px" 的寫法才是真正跨瀏覽器相容的方式;而讀取時使用 offsetHeight、offsetWidth 則各家瀏覽器都能正確取得。

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