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

如何将-webkit-line-clamp生成的省略号替换为“查看更多”链接

你要的效果可以通过CSS、JS两种方式实现,具体实现方案如下:

方案1:纯CSS实现

适合文本内容确定会超过限定行数的场景,实现成本最低:

  • 核心思路:禁用-webkit-line-clamp的默认省略号,通过绝对定位将「查看更多」固定在容器右下角,搭配同底色渐变遮挡末尾文字避免重叠。

代码示例:

.box {
  position: relative;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;  
  overflow: hidden;
  width: 300px;
  line-height: 1.5;
  background: #fff;
}
/* 遮挡默认省略号,处理文字和链接的衔接 */
.box::after {
  content: "";
  position: absolute;
  right: 0;
  bottom: 0;
  width: 80px;
  height: 1.5em;
  background: linear-gradient(to right, transparent, #fff 40%);
  pointer-events: none;
}
.more-link {
  position: absolute;
  right: 0;
  bottom: 0;
  color: #1677ff;
  text-decoration: none;
}
<div class="box">
  <p>Hey, don't cut me off like that. I want to speak my mind and don't appreciate being put into a box.</p>
  <a href="#" class="more-link">查看更多</a>
</div>

注意:该方案的局限性是无论文本是否超过3行,都会显示「查看更多」链接,仅适合内容长度固定且确定超出的场景。

方案2:JS实现(更推荐)

可以自动判断文本是否真的溢出,仅当内容超出限定行数时才显示「查看更多」链接,适配所有场景:

  • 核心思路:通过比较元素的scrollHeight和clientHeight判断内容是否溢出,溢出时才动态插入「查看更多」链接,同时配合原有截断逻辑保留排版。

代码示例:

.box {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;  
  overflow: hidden;
  width: 300px;
  line-height: 1.5;
  position: relative;
  padding-right: 70px;
}
.more-link {
  position: absolute;
  right: 0;
  bottom: 0;
  color: #1677ff;
  text-decoration: none;
  background: #fff;
}
const box = document.querySelector('.box')
const content = box.querySelector('p')
// 判断内容是否溢出
if (content.scrollHeight > box.clientHeight) {
  const moreLink = document.createElement('a')
  moreLink.href = '#'
  moreLink.className = 'more-link'
  moreLink.innerText = '查看更多'
  box.appendChild(moreLink)
}
<div class="box">
  <p>Hey, don't cut me off like that. I want to speak my mind and don't appreciate being put into a box.</p>
</div>

内容的提问来源于stack exchange,提问作者AdityaHM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:54:04