Vue 文本超过三行展示省略号,并加上展开和收起的功能

3,502 阅读1分钟

Vue 文本超过三行展示省略号,并加上展开和收起的功能

具体实现思路如下:

  • 1、判断当前内容是否超过三行。此处可以给每行设置一个行高line-height,渲染完后超过三倍的行高即认为是内容超过了三行。(因为后台返回的数据是富文本录入的,每行没固定高,所以样式改为显示3行)
  • 2、展示/收起状态的切换可以通过data中的参数来绑定
  • 3、在底部使用position:absolute来绝对定位展开该在的位置。
  • 4、根据业务需求来设定好展开和收起按钮的地方。 具体实现代码:

DOM

    <div class="content-wrap">

      <div :class="['content', expande ? 'expande' : 'close']" ref="content" v-html="summary">
      </div>
      <div class="expande-button-wrap" v-if="needShowExpande">
          <div class="expande-button" @click="expandeClick" v-if="!expande">展开
          </div>
          <div class="expande-button" @click="expandeClick" v-else>收起</div>
      </div>
    </div>

Script

export default {
    data() {
        return {
              expande: true,
              needShowExpande: false,
              summary: ''
         }
    },
    mounted() {
        this.summaryHeight()
    },
    methods: {
        expandeClick() {
            this.expande = !this.expande
        },
        summaryHeight(){
            this.$nextTick(() => {
                let lineHeight = 22
                if (this.$refs.content.offsetHeight > lineHeight * 3) {
                    this.expande = false
                    this.needShowExpande = true
                } else {
                    this.expande = true
                }
            })
        },
    }
}

css

<style >
    .content {
        font-size: 14px;
        color: black;
        letter-spacing: 0;
        line-height: 22px;
        text-align: justify;
        overflow: hidden;
        /* display: -webkit-box; */
        /* -webkit-line-clamp: 3;
        -webkit-box-orient: vertical; */
        /* text-overflow: ellipsis; */
    }

    .expande {
        overflow: auto;
        height: auto;
        padding-bottom: 22px;
    }

    .close {
        word-break: break-all;
        overflow: hidden;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        text-overflow: ellipsis;
        display: -webkit-box;
        /*overflow: hidden;
        height: 66px;
        padding-bottom: 0;*/
    }

    .expande-button-wrap {
        position: absolute;
        bottom: 0;
        right: 0;
        height: 22px;
        background: white;
    }

    .expande-button {
        text-align: right;
        vertical-align: middle;
        color: #5995ef;
        font-size: 14px;
        line-height: 22px;
    }
</style>

其中需要注意的点有

  • 展开收起按钮的高度和行高要和原来文本的行高一致,不然会导致样式不统一。
  • 获取文本的高度时要注意使用this.$nextTick()来保证DOM渲染完成后再获取高度
  • 在不同场景下省略号可能不能够完全遮住最后几个字,可以通过调节空格,字体排布方式等办法来调整,或者不要把展开和文本放在同一行,另起一行并且在末尾打开省略文本的样式 原文