Tooltip component: judge whether to display Tooltip according to whether the content overflows

This component is a secondary encapsulation of the el-tooltip component in Element UI

New feature: When the mouse moves into the parent node, it is judged whether to display Tooltip according to whether the content overflows

el-tooltip documentation

<template>
    <!-- 
        属性
            content:el-tooltip 属性,文本内容
            effect:el-tooltip 属性,Tooltip 主题,默认 light
            placement:el-tooltip 属性,Tooltip 显示的方向,默认值为 top
     -->
    <el-tooltip :disabled="disabled" :content="content" :effect="effect" :placement="placement">
        <span class="j-tooltip" ref="content">{
    
    {
    
    content}}</span>
    </el-tooltip>
</template>

<script>

export default {
    
    
    name: 'JTooltip',
    props: {
    
    
        content: String,
        effect: {
    
    
            type: String,
            default: 'light'
        },
        placement: {
    
    
            type: String,
            default: 'top'
        }
    },
    data() {
    
    
        return {
    
    
            disabled: false
        }
    },
    mounted() {
    
    
        const parentNode = this.$refs.content.parentNode;
        parentNode.addEventListener('mouseenter', this.handleMouseenter);
    },
    methods: {
    
    
        handleMouseenter(e) {
    
    
            this.disabled = !this.textOverflow(e.target);
        },

        // 判断文本是否溢出
        textOverflow(element) {
    
    
            const range = document.createRange();
            range.setStart(element, 0);
            range.setEnd(element, element.childNodes.length);
            const rangeWidth = range.getBoundingClientRect().width;
            const computed = window.getComputedStyle(element)
            const padding = (parseInt(computed.paddingLeft, 10) || 0) + (parseInt(computed.paddingRight, 10) || 0);

            return rangeWidth + padding > element.offsetWidth || element.scrollWidth > element.offsetWidth;
        },
    },
    beforeDestroy() {
    
    
        const parentNode = this.$refs.content.parentNode;
        if (parentNode) {
    
    
            parentNode.removeEventListener('mouseenter', this.handleMouseenter);
        }
    },
}
</script>

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

Guess you like

Origin blog.csdn.net/dark_cy/article/details/124327055