JavaScript实现文字省略与展开的核心是CSS截断+JS状态切换:先用white-space/overflow或-webkit-line-clamp实现单/多行省略,再通过scrollHeight>clientHeight检测溢出,动态添加按钮并切换max-height及文本内容。

JavaScript 中实现文字超出显示省略号并支持点击展开全文,核心是结合 CSS 控制截断 + JS 切换状态。关键在于动态判断内容是否溢出,并控制容器高度或行数。
1. 基础 CSS 截断(单行/多行省略)
先用 CSS 实现默认省略效果,这是前提:
-
单行省略:用
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; -
多行省略(WebKit 浏览器):用
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;(注意:仅 Safari/Chrome 有效,Firefox 不支持)
2. JS 动态检测是否溢出并添加展开按钮
CSS 多行截断无法精确判断是否真的被截断,所以需 JS 辅助测量。常用方法是对比滚动高度与可视高度:
- 给文字容器设固定最大行高(如
line-height: 1.5),再乘以期望行数(如 2 行 →max-height: 3em) - 用
element.scrollHeight > element.clientHeight判断是否溢出 - 若溢出,插入「展开」按钮,并绑定点击事件
3. 点击展开的实现方式(推荐)
不推荐直接修改 -webkit-line-clamp(不可靠),更稳妥的是切换 class 控制高度:
立即学习“Java免费学习笔记(深入)”;
- 默认样式:
.text { max-height: 3em; overflow: hidden; } - 展开后样式:
.text.expanded { max-height: none; } - JS 中切换
element.classList.toggle('expanded') - 可选:添加 CSS 过渡(
max-height需设具体值才可过渡,可用height: auto+overflow: visible配合scrollHeight动态设置过渡目标值)
4. 完整示例代码(含折叠逻辑)
HTML:
<div class="text-container"><div class="text">这是一段很长的文字……</div>
<button class="toggle-btn">展开</button>
</div>
JS:
const container = document.querySelector('.text-container');const text = container.querySelector('.text');
const btn = container.querySelector('.toggle-btn');
// 初始判断是否需要截断
const lineHeight = parseFloat(getComputedStyle(text).lineHeight);
const maxHeight = lineHeight * 2; // 限制 2 行
if (text.scrollHeight > maxHeight) {
text.style.maxHeight = maxHeight + 'px';
btn.style.display = 'inline';
btn.addEventListener('click', () => {
if (text.classList.contains('expanded')) {
text.classList.remove('expanded');
text.style.maxHeight = maxHeight + 'px';
btn.textContent = '展开';
} else {
text.classList.add('expanded');
text.style.maxHeight = 'none';
btn.textContent = '收起';
}
});
} else {
btn.style.display = 'none';
}


















