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

React实现文本截断显示省略号并添加行内展开按钮

解决文本截断+展开按钮重叠/被截断问题

核心思路是给文本容器预留按钮空间,通过绝对定位放置按钮,避免和省略号重叠,同时确保按钮不被文本截断规则影响。

步骤1:调整HTML结构

将展开按钮与文本容器同级放置,彻底脱离文本截断规则的影响范围:

<div className={styles['all-text']}>
  <span className={`${isExpanded ? '' : styles['overflow']}`}>
    <b>{t('subtitle')}&nbsp;</b>
    {ingredients}
  </span>
  <span 
    className={`${styles['text-expander']} ${isExpanded ? styles['expanded'] : ''}`}
    onClick={() => setIsExpanded(!isExpanded)}
  >
    {isExpanded ? t('collapse') : t('view-more')}
  </span>
</div>

步骤2:修改CSS样式

  • 给父容器设置相对定位,作为按钮定位的基准
  • 给截断文本容器添加底部内边距,避免文本被按钮遮挡
  • 按钮绝对定位在右下角,展开时回归正常文档流
.all-text {
  @include typ-body-1-16-regular;
  margin-bottom: calc(1.5 * #{$default-padding});
  position: relative; /* 新增:作为按钮定位的参考容器 */

  @include xs-mobile {
    @include typ-body-2-14-regular;
    text-align: left;
  }

  & .overflow {
    @include max-width-for-ingreients;
    display: block;

    @include xs-mobile {
      text-overflow: ellipsis; /* 修正为显示省略号 */
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 4;
      -webkit-box-orient: vertical;
      padding-bottom: 20px; /* 新增:给按钮预留显示空间 */
    }
  }

  & .text-expander {
    display: none;
    text-decoration: underline;

    @include xs-mobile {
      display: inline-block;
      cursor: pointer;
      background-color: $white;
      position: absolute; /* 改为绝对定位,脱离文本流 */
      bottom: 0;
      right: 0;
      padding-left: 8px; /* 新增:覆盖文本末尾区域,避免与省略号视觉重叠 */

      &.expanded {
        position: static; /* 展开时回到正常文档流 */
        padding-left: 0;
        margin-top: 8px;
      }
    }
  }
}

关键说明

  1. 父容器的position: relative确保按钮的绝对定位不会超出文本块范围
  2. .overflow的padding-bottom让文本最后一行不会被按钮遮挡
  3. 按钮的padding-left可以覆盖文本末尾的省略号区域,解决重叠问题
  4. 展开状态下按钮回归正常流,避免破坏整体布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:15:27