You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript获取CSS截断后的文本长度?

获取CSS截断后的实际文本长度

当你用white-space: nowrap; overflow: hidden; text-overflow: ellipsis;实现单行文本截断后,直接通过innerText.length拿到的是原始完整文本的长度,根本不是页面上显示的截断后文本长度。比如下面的例子:

示例代码

HTML:

<div id="txt" style="font-size: 0.9em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
  Value soooo soooo lognnng Value soooo soooo lognnng Value soooo soooo lognnng Value soooo soooo
</div>

JS:

const div = document.querySelector('#txt')
console.log(div.innerText.length) // 输出原始文本长度83,而非截断后的28

解决方法

方法一:用Range API检测可见文本

Range API能精确捕捉容器内可见的文本范围,代码如下:

function getTruncatedTextLength(element) {
  const rect = element.getBoundingClientRect();
  const range = document.createRange();
  range.setStart(element.firstChild, 0);
  
  let endOffset = 0;
  // 逐步扩展范围直到超出容器宽度
  while (true) {
    try {
      range.setEnd(element.firstChild, endOffset + 1);
    } catch (e) {
      break;
    }
    const rangeWidth = range.getBoundingClientRect().width;
    if (rangeWidth > rect.width) break;
    endOffset++;
  }
  
  // 减去1是为了给省略号留出空间,再加上省略号的3个字符长度
  return (endOffset - 1) + 3;
}

// 使用
const div = document.querySelector('#txt');
console.log(getTruncatedTextLength(div)); // 输出28

方法二:克隆元素逐步截断文本

创建一个和原元素样式完全一致的隐藏克隆元素,用二分法找到刚好能容纳的最长文本,再加上省略号长度:

function getTruncatedTextLength(element) {
  const clone = element.cloneNode(true);
  // 隐藏克隆元素但保留布局计算
  clone.style.position = 'absolute';
  clone.style.visibility = 'hidden';
  clone.style.overflow = 'visible';
  clone.style.textOverflow = 'clip';
  document.body.appendChild(clone);
  
  const originalWidth = element.getBoundingClientRect().width;
  const fullText = element.textContent;
  
  let left = 0;
  let right = fullText.length;
  let maxVisibleLength = 0;
  
  // 二分法查找最大可见文本长度
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    clone.textContent = fullText.slice(0, mid);
    const cloneWidth = clone.getBoundingClientRect().width;
    
    if (cloneWidth <= originalWidth) {
      maxVisibleLength = mid;
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  
  document.body.removeChild(clone);
  // 加上省略号的3个字符
  return maxVisibleLength + 3;
}

// 使用
const div = document.querySelector('#txt');
console.log(getTruncatedTextLength(div)); // 输出28

注意:如果你的text-overflow用了自定义省略符(比如text-overflow: ">>"),记得把代码里的3改成对应省略符的字符数。

内容的提问来源于stack exchange,提问作者Josemilson Júnior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:01:09