如何移除CSS省略号截断后HTML元素的剩余文本(保持容器高度)
问题描述
使用CSS规则 text-overflow: ellipsis; 和 -webkit-line-clamp:3; 实现文本截断时,偶尔会出现下一行显示少量像素的问题。由于element.innerHTML不会返回省略号,无法通过正则检测移除多余文本,需要解决如何移除HTML元素中省略号后的剩余文本,同时保持示例中div的高度不变。
现有代码示例
HTML
<div id='header-inner'></div>
CSS
#header-inner { height: 80px; display: -webkit-box; font-size: 15px; font-weight: normal; font-style: normal; text-decoration: none; border-width: 1px; max-height: 62px; text-overflow: ellipsis; overflow: hidden; -moz-box-orient: vertical; white-space: unset; -webkit-line-clamp: 3; padding-top: 0px; }
JavaScript
let ele = document.getElementById('header-inner'); ele.innerHTML = 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which ';
解决方案
可以通过逐字符移除文本并检测元素滚动高度的方式精准截断文本,确保多余文本被完全移除,同时保持容器高度不变。
实现代码
function trimOverflowText(elem) { const maxHeight = parseInt(window.getComputedStyle(elem).maxHeight); // 内容未超出高度,无需处理 if (elem.scrollHeight <= maxHeight) return; let text = elem.textContent; // 从后往前删字符,直到内容高度符合要求,同时手动补省略号 while (elem.scrollHeight > maxHeight && text.length > 0) { text = text.slice(0, -1); elem.textContent = text + '...'; } } // 调用示例 let ele = document.getElementById('header-inner'); ele.innerHTML = 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which '; // 等DOM渲染完成后执行截断 setTimeout(() => trimOverflowText(ele), 0);
说明
- 通过
scrollHeight对比maxHeight,判断内容是否超出容器 - 逐字符删除末尾文本并手动添加省略号,直到内容高度不超过容器限制
- 保留原有CSS的高度、溢出设置,确保布局完全不变
内容的提问来源于stack exchange,提问作者Gustė
相关产品推荐
相关产品推荐

