多行文本省略号的收起、展开

实现效果

超过两行显示 省略号 + 展开
点击展开之后,在文字后显示 收起
在这里插入图片描述在这里插入图片描述

代码部分

仅说明企业简介内容部分

  1. 对需要省略的内容设置唯一id【content-${item.id}】,进行多行省略处理【类名introduction】
  2. 通过id获取元素,判断展示高度 是否小于 滚动高度,若小于滚动高度则需要折叠【moreDisplay[item.id] 为 true】
  3. 默认为折叠状态【item.folding 为 true】,将 省略号展开 绝对定位在右下角
  4. 当切换为非折叠状态时【item.folding 为 false】,将 收起 接在文本内容后面,取消多行省略处理【类名all_text】

HTML

<span :id="`content-${item.id}`" :class="['introduction', item.folding ? '' : 'all_text']">
  {{ item.introduction || '-' }}
  <template v-if="moreDisplay[item.id]">
    <div v-show="item.folding" class="more">
      <div class="ellipsis">...</div>
      <div class="expand" @click.stop="showUp(item)">展开</div>
    </div>
    <span v-show="!item.folding" style="color: #0091FA" @click.stop="showUp(item)">收起</span>
  </template>
</span>

JS

import _ from 'lodash';
watch: {
  dataList() {
  	// 列表改变时重新计算是否需要折叠,用debounce防抖
    this.updateMoreDisplay();
  }
},
methods: {
  showUp(item) {
    item.folding = !item.folding
  },
  updateMoreDisplay: _.debounce(function () {
    const display = {};
    this.dataList.forEach((item) => {
      var content = document.getElementById(`content-${item.id}`);
      if (content && content.clientHeight < content.scrollHeight) {
        display[item.id] = true;
      } else {
        display[item.id] = false;
      }
    })
    this.moreDisplay = display;
  }, 300),
}

js部分处理完成。
如果为详情页面,数据不会动态变化,无需监听,可在初始化函数内用setInterval处理,例如:

  let timer = null;
timer = setInterval(() => {
  const content = document.getElementById('content-introduction');
  content && clearInterval(timer);
  if (content && content.clientHeight < content.scrollHeight) {
    this.isShowMore = true;
  } else {
    this.isShowMore = false;
  }
}, 300)

CSS

// 下面introduction中的 width: 0; flex: 1;是为了在当前特定样式下占剩余宽度的100%;如果本身就是一整行则替换为 width: 100%
.introduction {
  position: relative;
  width: 0;
  flex: 1;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.all_text {
  -webkit-line-clamp: inherit;
}

.more {
  box-sizing: border-box;
  position: absolute;
  width: 58px;
  right: 0;
  bottom: 0;
  padding-left: 4px;
  background-color: #fff;
}
/* 省略号 */
.ellipsis {
  float: left;
}
/* 展开收起按钮 */
.expand {
  float: right;
  color: #0091FA;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值