如何获取固定宽高div内部文本的实际宽高尺寸
你之前通过jQuery调用height()、innerHeight()、outerHeight()拿到的是被固定宽高限制后的div元素自身尺寸,并非内部文本的真实渲染尺寸,可通过以下两种方案获取文本实际宽高:
方案1:使用原生Range API(推荐)
Range API可以直接选中元素内的所有文本内容,计算得到其真实渲染的边界尺寸,无需修改原有DOM:
function getTextRealSize(element) { const range = document.createRange(); range.selectNodeContents(element); const rect = range.getBoundingClientRect(); return { width: rect.width, height: rect.height }; } // 调用示例 const targetDiv = document.querySelector('div'); const realSize = getTextRealSize(targetDiv); // realSize.width 为文本真实宽度,realSize.height 为文本真实高度
方案2:克隆元素临时计算(兼容低版本浏览器)
如果需要兼容不支持Range API的老旧浏览器,可以通过克隆原元素、临时移除固定尺寸限制后计算尺寸:
function getTextRealSizeByClone(element) { // 克隆原元素完整内容和样式 const cloneEle = element.cloneNode(true); // 移除固定宽高限制,设置为不可见、不占用页面布局 cloneEle.style.cssText += ` width: auto !important; height: auto !important; position: absolute !important; visibility: hidden !important; left: -9999px !important; top: -9999px !important; `; document.body.appendChild(cloneEle); // 获取真实尺寸后移除克隆元素 const realSize = { width: cloneEle.offsetWidth, height: cloneEle.offsetHeight }; document.body.removeChild(cloneEle); return realSize; }
两种方案均适配你提到的两种场景:单字符字号超过容器尺寸、长文本多行溢出容器的情况,都能返回正确的文本真实宽高。
内容的提问来源于stack exchange,提问作者neubert
相关产品推荐
相关产品推荐

