隱藏元素 (display: none) 在文檔流中不佔據空間,直接讀取 offsetWidth/Height 會得到 0。常見解決方案是「克隆→絕對定位移出視口→顯示→測量→銷毀」。
// 兼容性獲取計算樣式
function getCss(elem, prop) {
if (window.getComputedStyle) return window.getComputedStyle(elem, null)[prop];
if (elem.currentStyle) return elem.currentStyle[prop];
return elem.style[prop];
}
// 核心:獲取寬高
function getWH(dom) {
const get = (elem) => {
const wh = {};
['Width', 'Height'].forEach(key => {
const k = key.toLowerCase();
wh[k] = elem['offset' + key] || elem['client' + key];
});
return wh;
};
if (getCss(dom, 'display') === 'none') {
const clone = dom.cloneNode(true);
clone.style.cssText = 'position:absolute;top:-3000px;display:block;';
document.body.appendChild(clone);
const wh = get(clone);
clone.parentNode.removeChild(clone);
return wh;
}
return get(dom);
}
// 測試
console.log(getWH(document.getElementById('content')));
若項目環境允許,可優先考慮 getBoundingClientRect() 配合 visibility: hidden 而非 display: none,或使用 requestAnimationFrame 在下一幀測量。但上述克隆法兼容性最強(IE6+),仍是庫級工具函數的標準實現。