在 Web 編輯器、代碼檢視、終端機模擬等場景中,內容寬度動態變化,需讓容器自適應內容寬度,同時正確觸發滾動條、不遮蔽內容、不留白邊。本文總結一套高精度、高效能、無試探迴圈的自適應寬度計算方案。
width: auto 受限於父級寬度,內容超寬會換行或溢出。white-space: nowrap 強制不換行,但無法自動撐開容器寬度,滾動條出現時內容可能被遮擋或出現雙重滾動條。scrollWidth 迭代),效能差、易抖動、邊界情況難處理。white-space: nowrap 於父容器,確保所有內容單行顯示,獲得真實寬度。width/height、margin/border/padding)body 末尾建立隱形 <span>,複製目標文字節點的**所有計算樣式** (font-family, font-size, font-weight, letter-spacing, word-spacing, text-transform…)。white-space: nowrap、visibility: hidden、position: absolute。offsetWidth / getBoundingClientRect().width。maxWidth。white-space: nowrap,恢復原始換行行為。container.style.width = (maxWidth + 6~8) + 'px'。
| 維度 | 傳統試探法 | 本方案 (單次遍歷精確計算) |
|---|---|---|
| 計算精度 | 依賴迭代收斂,邊界易誤差 ±1px | 像素級精確,含 margin/border/padding 完整盒模型 |
| 效能 | O(n × 迭代次數),大文檔明顯卡頓 | O(n) 單次遍歷,無迴圈,大文檔毫秒級完成 |
| 穩定性 | 迴圈可能不收斂、抖動 | 確定性算法,無抖動、無死循環 |
| 滾動條適配 | 常需額外 hack | 預留寬度機制天然解決 |
function getComputedStyleProps(el) {
const cs = window.getComputedStyle(el);
return {
fontFamily: cs.fontFamily,
fontSize: cs.fontSize,
fontWeight: cs.fontWeight,
fontStyle: cs.fontStyle,
letterSpacing: cs.letterSpacing,
wordSpacing: cs.wordSpacing,
textTransform: cs.textTransform,
// ... 其他影響寬度的屬性
};
}
const ruler = document.createElement('span');
ruler.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap;top:-9999px;left:-9999px;';
document.body.appendChild(ruler);
function measureText(text, styleProps) {
Object.assign(ruler.style, styleProps);
ruler.textContent = text;
return ruler.getBoundingClientRect().width;
}
function getElementWidth(el) {
const cs = window.getComputedStyle(el);
const rect = el.getBoundingClientRect();
// 含 margin
return rect.width +
parseFloat(cs.marginLeft) +
parseFloat(cs.marginRight);
}
font-family 鏈,否則系統回退字體導致寬度偏差。getBoundingClientRect() 回傳浮點數,累加時保留浮點,最終 Math.ceil() 取整。transform/scale 會影響 getBoundingClientRect,需在無 transform 環境測量或換算。ResizeObserver 或 MutationObserver 觸發。自適應寬度的本質是在受限環境中精確測量內容幾何尺寸。通過臨時禁用換行 + 單次遍歷 + 離屏測量元素 + 盒模型完整疊加 + 滾動條預留,可獲得生產級的精度與效能。此方案已在多個線上編輯器專案中驗證,歡迎根據業務場景調整細節 (如對中文字體、emoji、連字符的特殊處理)。