日常开发记录-ElementUI el-toolTip组件封装多行文本超出隐藏

该博客介绍了如何在Vue中创建一个自定义组件,该组件可以实现文本超出指定行数时自动省略,并通过Tooltip显示完整内容。组件支持动态绑定样式和点击链接跳转功能,当鼠标悬停在文本上时,如果文本超出限制,则显示Tooltip提示,否则不显示。文章还提供了详细的代码示例和使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载根据需求适当做了调整

作者:ShineShadow
链接:https://juejin.cn/post/7007729080145543182

组件:

<template>
    <el-tooltip :content="txtInfo" placement="top" effect="light" :disabled="isShow">
     <!-- :style="dynamicSty"动态绑定样式  -->
        <div class="contentnowrap" :style="dynamicSty" :class="{isLink: 'link-text'}" @mouseenter="isShowTooltip" @click="linkTo">
          <span ref="contentRef">{{ txtInfo }}</span>
        </div>
    </el-tooltip>
</template>
<script>
export default {
  name: 'toolTip',
  props: {
    txtInfo: {
      type: String,
      default: ''
    },
    num: {
      type: Number,
      default: 1
    },
    isLink: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      isShow: false,
      dynamicSty: {
        '-webkit-line-clamp': this.num // 这里是超出几行省略
      }
    }
  },
  methods: {
    isShowTooltip (e) {
      const clientHeight = e.target.clientHeight
      const scrollHeight = e.target.scrollHeight
      const arrList = Array.from(e.target.classList)
    // 文字超出隐藏并弹出tooltip提示,文字未超出则不弹出tooltip提示的判断条件
      if (scrollHeight > clientHeight && this.$refs.contentRef.parentNode.offsetWidth > this.$refs.contentRef.offsetWidth) {
        this.isShow = false
        if (!arrList.includes('hover-blue')) {
          e.target.classList.add('hover-blue')
        }
      } else {
        this.isShow = true
        e.target.classList.remove('hover-blue')
      }
    },
    linkTo () {
      if (this.isLink) {
        this.$emit('linkTo')
      }
    }
  }
}
</script>
<style lang="scss">
    .contentnowrap{
        padding: 2px 0;
        word-break: break-all;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    .hover-blue:hover{
        color: red;
    }
    .link-text{
        color: red;
        cursor: pointer;
    }
    .el-tooltip__popper{
        font-size: 14px;
        font-family: 'Microsoft YaHei';
    }
</style>

使用:

<template>
  <div style="width:200px;height:60px;border:2px solid red;">
    <tool-tip v-bind='{
      txtInfo: "文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字",
      num:2
      }'>
    </tool-tip>
  </div>
</template>
<script>
import toolTip from './components/toolTip.vue'
export default {
  components: { toolTip },
  data () {
    return {}
  }
}
</script>
<style>
</style>

 效果展示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值