前端实现文本展开收起

文本的展开收起是我们网页常常需要优化处理的操作

需求描述:文本内容若一行能够展示完,则不需要更多/收起按钮;若不能则需单行文本省略展示并显示更多/收起按钮可供操作

html代码段:

<div class="stu-con" >
   <div :class="showMore? 'oneLine' : 'allLine'" >
      {{ specialInfoData.description }}
   </div>
   <span 
     style="width: 70px;margin-left:10px;"
     @click="handleShowMore"
     id="more"
     v-if="showMoreBtn"
   >
    {{ showMore ? '更多' : '收起'}}
    <i :class="{'qw-icon-arrow-down': showMore, 'qw-icon-arrow-top': !showMore}" />
    </span>
</div>

js代码段

data () {
    return {
      showMore: false, // 控制更多/收起按钮的切换
      showMoreBtn: false, // 控制更多/收起按钮的展示和隐藏
    }
  },
methods: {
    // 计算字符数
    byteCount(str) {
      const count = (str && str.replace(/[^\x00-\xff]/g, "xx").length) || 0;
      return count;
    },
    // 更多/收起按钮的切换
    handleShowMore() {
      this.showMore= !this.showMore
    },
    getSpecialInfo () {
      getSpecialInfo({ id: this.id }, data => {
        this.specialInfoData = data.specialInfo || {}
        // 对需要展示的文本进行字符长度判断处理
        if(this.byteCount(this.specialInfoData.description) > 150) {
          this.showMore = true
          this.showMoreBtn = true
        } else {
          this.showMoreBtn = false
        }
      })
    },
}

css代码:

.oneLine {
  width: 640px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.allLine {
  max-width: 640px;
  height: auto;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值