基于el-element的el-tooltip封装的组件

909 阅读1分钟
在开发过程中遇到有内容描述的时候,会遇到这种情况,描述的区域有限,在描述文字过多的时候要添加...,把超出的部分省略掉,即
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
在超出的时候我们需要鼠标移上显示tooltip,在不超出的时候隐藏tooltip。
代码如下:
<--html-->
<el-tooltip 
    class="item"
    :disabled="isShowToolTip"
    :content="content"
    placement="top">
    <div class="tooltip" :ref="`fatherRef${index}`" @mouseover="mouseoverTip(index)"><span :ref="`sonRef${index}`">{{content}}</span></div>
</el-tooltip>

<--js-->
mouseoverTip(index) {
    // 父元素的宽
    const fatherW = this.$refs[`fatherRef${index}`].offsetWidth;
    // 子元素的宽
    const sonW = this.$refs[`sonRef${index}`].offsetWidth;
    // 当子元素的宽大于等于父元素时,显示tooltip
    this.isShowToolTip = !(sonW >= fatherW);
}

<--css-->
至少要给父元素一个最大宽或者是一个固定宽

.tooltip{
    max-width: 140px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

此方法为控制鼠标移上的时候,把tooltip的disabled属性切换true/false,已达到想要效果。

更新一下,发现在谷歌浏览器下,span的宽度会受限于父级div的宽度,这个时候判断子元素
和父元素的宽的时候就会永远小于等于父级的宽,导致出现了省略的时候,鼠标移上也不会触
发tooltip。解决办法是给父元素下的子元素span一个相对定位,即:
.tooltip{ 
    max-width: 140px; 
    overflow: hidden; 
    white-space: nowrap; 
    text-overflow: ellipsis; 
    span{
        position: relative;
    }
}