CSS:2行文字时正常显示,超过2行显示更多

在做页面时,ui有一个这样的需求,当描述中不超过2行文字时,则正常显示在页面上,超过2行的时候,显示更多

  1. 不能根据字数的多少判断行数,因为电脑屏幕大小不一样,故一行文字的字数也不同;
  2. 也不能用 -webkit-line-clamp: 2;因为这样“更多”无法显示,被隐藏的文字也无法显示

所以,用js搞定是比较好的。下面是实现思路

1、首先,假设2行文字的正常高度是40px。在请求描述内容成功之后,去获取描述内容div的高度,如果高度大于40px,则显示更多按钮,并折叠多余内容;

2、具体过程如下:

<div class="comment-abstract-layer">
 <div
    class="content-abstract-layer"
    ref="contentAbstractDom"
    :style="{height}"
    v-html="videoDetail.summary"
  ></div>
  <div v-if="isShowMoreBtn" class="more text-right" @click="isOpen = !isOpen">
    <img class="fold-icon vertical-align-middle" :src="imageUrl" />
  </div>
</div>
data() {
	return {
	    isOpen: true,
        isShowMoreBtn: false
	},
},
computed: {
  height() {
    	return this.isOpen ? "auto" : 40 + "px";
  },
  imageUrl() {
     return this.isOpen ? require("@/assets/img/icon_up.png") : require("@/assets/img/icon_down@2x.png");
   }
},
getVideoDetail() {
  return new Promise(resolve => {
     api
       .getVideoDetailById({
         id: this.videoId,
         deviceType: 1
       })
       .then(res => {
         this.videoDetail = res;
         this.doCountHeightLimit();  // doCountHeightLimit方法即是获得div高度的方法
         resolve();
       })
       .catch(err => {
         this.getVideoErrorCode = err.subCode;
       });
   });
},

async doCountHeightLimit() {
   this.isOpen = true;
   this.isShowMoreBtn = false;
   await this.$nextTick();
   let offsetHeight = this.$refs.contentAbstractDom.offsetHeight;
   if (offsetHeight > 40) {
     this.isOpen = false;
     this.isShowMoreBtn = true;
   }
 }
.comment-abstract-layer {
   position: relative;
   .content-abstract-layer {
     white-space: pre-line;
     margin: 20px 0 25px;
     overflow: hidden;
     text-align: justify;
     height: 40px;
   }
   .more {
     position: absolute;
     background: linear-gradient(to left, #ffffff, #ffffff 36%, rgba(255, 255, 255, 0));
     width: 60px;
     bottom: 0px;
     right: 1px;

     .fold-icon {
       width: 32px;
     }
   }
 }
posted @ 2025-05-10 08:49  Dy大叔  阅读(256)  评论(0)    收藏  举报