解决文件名超出时中间显示省略号,中文名与英文名长度显示不一致问题

在网上查看相关解决方案时发现一种大佬实现的很厉害的纯css方案,一开始的组件实现也是基于此,但是很快发现一个问题,因为右侧显示的时候使用 background 来隐藏左侧的文本,但是我们项目用的渐变背景,所以无法这么处理,所以结合 js 对这种方案做了一些改进,使得可以兼容我们的项目~代码如下:

<template>
  <div class="text-wrap">
    <span ref="textLeft" class="text-left">{{ text }}</span>
    <span ref="textRight" class="text-right" :title="text">{{ text }}</span>
  </div>
</template>

<script>
  export default {
    name: 'text-ellipsis-center',
    props: {
      text: {
        type: String,
        default: ''
      }
    },
    watch: {
      text: {
        immediate: true,
        handler() {
          this.$nextTick(() => {
            this.judgeShow()
          })
        }
      }
    },
    methods: {
      judgeShow() {
        const textLeftRef = this.$refs.textLeft
        const textRightRef = this.$refs.textRight

        if (textLeftRef.clientHeight < textRightRef.clientHeight + 1) {
          textLeftRef.style.color = '#1d1f24'
        } else {
          textLeftRef.style.color = 'transparent'
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .text-wrap {
    width: calc(100vw - 114px);
    // width: 300px;

    /* 设置正常行高,并隐藏溢出画面 */
    height: 2em;
    overflow: hidden;
    line-height: 2;
    position: relative;
    text-align: -webkit-match-parent;
    // resize: horizontal;
  }
  .text-left {
    /* 设置最大高度为双倍行高使其可以换行 */
    display: block;
    max-height: 4em;
    word-break: break-all;
    // color: #1d1f24;
  }
  .text-right {
    position: relative;
    top: -4em;
    display: block;
    color: #1d1f24;
    overflow: hidden;
    height: 2em;
    text-align: justify;
    // background: #f7f9fb;
    overflow: hidden;
    word-break: break-all;
  }

  .text-right::before {
    content: attr(title);
    width: 50%;
    margin-left: -5px;
    float: right;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    direction: rtl;
  }
</style>

通过判断当原本的文本 dom 高于右侧高度时,说明发生了换行,这时候不需要显示原本文本,所以进行隐藏,反之则显示

实现原理可以参考这里~

https://juejin.cn/post/7329967013923962895?searchId=20241208205727EA80D9D5FB0511F5EE2C#heading-7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值