功能展示:
当内容超过宽度时,溢出内容用省略号展示,鼠标辅导在内容上时,tooltip显示内容。
实现思路
- 容器要有固定宽度。且内容溢出时,展示省略号。
- 设置tooltip,鼠标进入时展示,并且只有内容溢出时候才展示,不溢出不展示内容
具体实现
溢出内容展示省略号
给容器添加css标签
div {
// 溢出内容不换行
white-space: nowrap;
// 隐藏溢出内容
overflow: hidden;
// 溢出内容展示为省略号
text-overflow: ellipsis;
}
给容器添加tooltip
tooltip在elementUI中有现成的实现。而我用的是自己写的组件
简单介绍一下实现结构:
<template>
<span @mouseover="mouseover" @mouseenter="mouseenter" @mousemove="mousemove" @mouseout="mouseout" @click="doClick" @touchstart="touchstart" @touchend="touchend" ref="tooltip">
<slot ref="slot"></slot>
<div class="el-tooltip__popper is-light" :class="customClass+'_tooltip'" :x-placement="placement" ref="div" @mouseover="mouseout" style="display:none">
<!-- v-text:防止存储型XSS漏洞,若使用v-html,后端需过滤字段 -->
<div v-if="isText" v-text="content"></div>
<div v-else v-html="content"></div>
<div x-arrow ref="arrow" class="popper__arrow"></div>
</div>
</span>
</template>
主要是通过slot插槽获得要展示的容器,鼠标浮动用绝对定位的盒子展示内容
主要看一下只在溢出时展示tooltip的逻辑
// 获取标记中的字段的span .ellipsis 元素
let fieldEllipsis = span.querySelector('.ellipsis');
if (fieldEllipsis) {
let clientWidth = fieldEllipsis.clientWidth;
let scrollWidth = fieldEllipsis.scrollWidth;
// 判断是否显示完全,不完全才需要弹出显示,完全显示跳出
if (clientWidth >= scrollWidth) {
return
}
}
if (this.onlyOverflow !== undefined && span.scrollWidth <= span.clientWidth) {
return
}
主要是获取dom元素中的省略号内容和非省略内容。通过比较他们的长度关系来判断是否溢出。
如果溢出则展示内容,不溢出则不展示。