這是一個經典難題:display: none 的元素不參與排版,offsetWidth 與 offsetHeight 都是 0,clientWidth 同樣是 0。若你需要先知道尺寸才能決定要不要顯示、或要對它做定位計算,就會卡住。
技巧是「暫時讓它參與排版,量完再移除」:
position: absolute,讓它脫離文件流、不影響其他元素。top 設成一個很大的負值(例如 -3000px),移到視界之外避免閃現。display: block 讓它開始計算尺寸。function getCss(elem, css){
if (window.getComputedStyle) {
return window.getComputedStyle(elem, null)[css];
} else if (elem.currentStyle) {
return elem.currentStyle[css]; // IE 舊版
} else {
return elem.style[css];
}
}
function getWH(dom){
var get = function(elem){
var wh = {};
'Width Height'.replace(/[^ ]+/g, function(i){
var a = i.toLowerCase();
wh[a] = elem['offset' + i] || elem['client' + i];
});
return wh;
};
if (getCss(dom, 'display') === 'none') {
var nDom = dom.cloneNode(true);
nDom.style.position = 'absolute';
nDom.style.top = '-3000px';
nDom.style.display = 'block';
document.getElementsByTagName('body')[0].appendChild(nDom);
var wh = get(nDom);
nDom.parentNode.removeChild(nDom);
return wh;
}
return get(dom);
}
// 測試
console.log(getWH(document.getElementById('content')));
'Width Height'.replace(/[^ ]+/g, ...) 是一個小技巧:拿字串當迭代器用,比寫兩次赋值簡短。用 offsetWidth || clientWidth 的 fallback 是為了處理某些 CSS 情境下 offset 為 0 的狀況。
cloneNode(true) 的副作用。複製出來的節點會帶著原本的 id,短時間內頁面上就有兩個相同 id 的元素。若在這期間有其他程式呼叫 document.getElementById,可能取到錯的那個。穩妥做法是在量完前先改掉 clone 的 id:
nDom.removeAttribute('id');
nDom.querySelectorAll('[id]').forEach(el => el.removeAttribute('id'));
clone 的表單元素不包含當前輸入值。若元素內有 input,clone 出來的是 HTML 屬性的預設值,不是使用者輸入的內容。量尺寸通常不受影響,但要知道這差異。
樣式必須完整。若寬度是由外部 CSS class 決定,clone 掛到 body 後仍會套用該 class,這通常沒問題。但若樣式依賴父元素的繼承(例如 width: 100%),脫離原本父層後量到的值就不對了。
方案一:用 visibility 代替 display。visibility: hidden 的元素仍然參與排版,所以尺寸是量得到的,只是看不見:
function getWH(el){
var old = el.style.visibility;
el.style.visibility = 'hidden';
el.style.display = 'block'; // 若原本是 display:none 仍需暫時改回
var wh = { width: el.offsetWidth, height: el.offsetHeight };
el.style.display = '';
el.style.visibility = old;
return wh;
}
注意 visibility: hidden 會保留佔位空間,若這會破壞版面,就要搭配 position: absolute。
方案二:用 getBoundingClientRect 並暫時掛上 off-screen 樣式
function measure(el){
var clone = el.cloneNode(true);
clone.style.cssText +=
';position:absolute;visibility:hidden;left:-9999px;top:0;display:block';
document.body.appendChild(clone);
var rect = clone.getBoundingClientRect();
document.body.removeChild(clone);
return { width: rect.width, height: rect.height };
}
用 visibility: hidden 而非移出視界,是因為 getBoundingClientRect 的回傳值不受位置影響(寬高照樣正確),而 visibility 能確保不會被看見。
方案三:先顯示再隱藏。最簡單粗暴:設 display: block; visibility: hidden,量完還原。程式碼最少,缺點是會造成一次額外的重排(reflow)。
原範例末尾測試程式中的 appendChild(o) 有個筆誤,變數名是 domA 而非 o,會拋出 ReferenceError。
最後提醒:位移與尺寸查詢會觸發 reflow,在迴圈中大量呼叫會明顯拖慢頁面。若需要連續讀寫樣式,記得批次化——先把所有讀取做完,再做寫入,避免「讀寫交錯」導致的強制同步排版。