用 JavaScript 讀取或設定 div 的寬高,看似簡單,但要在不同瀏覽器下都能正確運作,仍有幾個細節需要注意。以下示範相容 FF 與 IE 的寫法。
<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>
alert(document.getElementById("div1").offsetHeight); //兼容 FF、IE 等
alert(document.getElementById("div1").offsetWidth); //兼容 FF、IE 等
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 則各家瀏覽器都能正確取得。