文字超出几行...展开效果

最近工作上遇到个文字超出几行… 展开的效果,一时不知道怎么做。后来有同事发现了heyUI有这样的组件,立马去他源码学习了一波。可参考源版HeyUI,本人只是借鉴hey UI官网
最终效果如下
在这里插入图片描述
展开后如下图
在这里插入图片描述

组件

<template>
  <div class="text-ellipsis">
    <span :content="text">
      <span class="text-ellipsis-limit-text" :key="keyIndex">{{ text }}</span
      ><span
        class="text-ellipsis-more"
        v-show="oversize"
        @click="isLimitHeight = false"
        ><slot name="more"
          ><span>...</span><span class="expand">展开</span></slot
        ></span
      >
    </span>
  </div>
</template>
<script>
export default {
  name: 'TextEllipsis',
  props: {
    text: String,
    maxLine: Number,
    lineHeight: Number
  },
  data () {
    return {
      keyIndex: 0,
      oversize: false,
      isLimitHeight: true
    };
  },
  computed: {
    height () {
      return this.maxLine * this.lineHeight * (document.documentElement.clientWidth / 375)
    }
  },
  watch: {
    text () {
      this.init();
    },
    isLimitHeight () {
      this.init();
    }
  },
  mounted () {
    this.init();
  },
  methods: {
    init () {
      this.oversize = false;
      this.keyIndex += 1;
      let more = this.$el.querySelector('.text-ellipsis-more');
      more.style.display = 'none';
      if (this.isLimitHeight) {
        this.limitShow();
      }
    },
    textClick () {
      this.$emit('click');
    },
    limitShow () {
      this.$nextTick(() => {
        let textDom = this.$el.querySelector('.text-ellipsis-limit-text');
        let title = this.$el;
        let more = this.$el.querySelector('.text-ellipsis-more');
        let n = 1000;
        if (textDom) {
          if (title.offsetHeight > this.height) {
            more.style.display = 'inline-block';
            let text = this.text;
            while (title.offsetHeight > this.height && n > 0) {
              if (title.offsetHeight > this.height * 3) {
                textDom.innerText = text = text.substring(0, Math.floor(text.length / 2));
              } else {
                textDom.innerText = text = text.substring(0, text.length - 1);
              }
              n--;
            }
          }
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.text-ellipsis {
  font-size: 14px;
  line-height: 24px;
  .expand {
    color: #3b91ff;
    padding-left: 14px;
  }
}
</style>

引用
超出3行打点展示

<text-ellipsis :text="text" :maxLine="3" :lineHeight="24"></text-ellipsis>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值