element-plus中的tooltip组件实现文字溢出显示省略号,悬浮显示tooltip完整信息

前言

需求:要求单行显示文字,溢出部分需要显示省略号,但鼠标悬浮时需要显示 tooltip 完整信息。
关键点:文字溢出显示省略号就不说了,主要是如何判断什么时候需要显示 tooltip,什么时候不显示。
思路:如果文字省略时,子元素的宽度势必小于父元素的宽度,则可通过监听鼠标移入事件,判断父子元素的宽度知道文字是否溢出,从而动态控制 tooltip 的显示。

<template>
    <el-tooltip
        :disabled="isShowTooltip"
        :content="text"
        placement="top"
        effect="light"
    >
        <div
            class="ellipsis"
            @mouseover="onMouseOver(refName)"
        >
            <span :ref="refName">{{ text }}</span>
        </div>
    </el-tooltip>
</template>

<script>
    export default {
        data() {
            return {
                isShowTooltip: true,
            }
        },
        props: {
            text: {
                type: String,
                required: true
            },
            refName: {
                type: String,
                required: true
            }
        },
        methods: {
            onMouseOver(refName) {
                const parentWidth = this.$refs[refName].parentNode.offsetWidth;
                const contentWidth = this.$refs[refName].offsetWidth;
                // 判断是否开启 tooltip 功能,如果溢出显示省略号,则子元素的宽度势必短于父元素的宽度
                if (contentWidth > parentWidth) {
                    this.isShowTooltip = false;
                } else {
                    this.isShowTooltip = true;
                }
            }
        }
    };
</script>

<style lang="less" scoped>
    .ellipsis {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值