文本超出两行显示省略号并有“展开”“收起”按钮效果(VUE环境)

文本超出两行显示省略号的效果使用css3可以很轻松地实现,但是要判断什么时候显示“展开”“收起”按钮却有点麻烦。如果单纯通过字数来判断的话,在有些客户端可能会判断错误,而且中英文的字符所占的位置也有所不同。下面介绍一种通过js计算实现的方法。

1、通过css实现文本超出两行显示省略号

html:

<!--在需要实现该效果的元素上设置class值ellipsis,并设置ref属性值infoItem-->
<p ref="infoItem" class="ellipsis" :class="{'more':showMore}">{{list.text}}
    <i class="switch-arrow" :class="showMore?'arrow-up':'arrow-down'" 
        v-if="hasMoreArrow" 
        @click="showMore=!showMore"/>
</p>

scss :

.ellipsis{
   position: relative;
   padding-right:3px;
   overflow:hidden; 
   word-break: break-all;
   text-overflow:ellipsis;
   display:-webkit-box; 
   -webkit-box-orient:vertical;
   -webkit-line-clamp:2; 
      &.more{
        display:block;
        text-overflow:initial;
    }
    .switch-arrow{
        position:absolute;
        right:-2px;
        bottom:-2px;
        color:#000;
        border: 6px solid transparent;
        border-left-width: 24px;
        border-right-width: 0;
        border-color:transparent;
        &:before{
          background-color:#fff;
        }
     }
}

2、 在mounted钩子函数中计算是否需要显示“展开”“收起”按钮

let cellChild=this.$refs.infoItem
this.hasMoreArrow=cellChild.scrollHeight>cellChild.offsetHeight

最终显示效果如下:

***如果是显示一行,超出部分用省略号显示,这种情况就需要判断元素的宽度了

scss修改如下:

.ellipsis{
   position: relative;
   padding-right:3px;
   overflow:hidden; 
   word-break: break-all;
   text-overflow:ellipsis;
   white-space: nowrap;
     &.more{
       display:block;
       text-overflow:initial;
       white-space: initial;
   }
}

js修改如下:

let cellChild=this.$refs.infoItem
this.hasMoreArrow=cellChild.scrollWidth>cellChild.offsetWidth

效果如下:

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值