一、前言
实现功能:基于vue3
,如果文本内容超过两行显示...,且鼠标移入显示气泡。
二、需求
表格所展示的某行某列的文本内容,如果超过两行则显示...,且鼠标滑上气泡展示全部文本,否则正常显示。
三、实现思路
根据该dom,获取到scrollHeight(元素内容的高度,包括溢出的不可见内容)
和clientHeight(元素实际显示出来的内容的高度)
,如果scrollHeight > clientHeight
,则溢出了,开启鼠标滑上气泡展示全部内容。
当然,如果是判断单行文本溢出,气泡展示,则根据scrollWidth > clientWidth
来判断溢出。
四、关键代码
抽离组件如下:
<template>
<div class="overflow-tooltip">
<el-tooltip v-if="content" effect="dark" placement="top" :disabled="!hasShowTips">
<div :class="`text-row-${row}`" @mouseenter="showTips">{{ content }}</div>
<template #content>
<div :style="{'max-width': width+'px'}">{{ content }}</div>
</template>
</el-tooltip>
</div>
</template>
<script setup>
import { ref } from "vue"
const props = defineProps({
content: String, // 内容
row: { // 行数
type: Number,
default: 2,
},
})
const hasShowTips = ref(false)
const width = ref("")
const showTips = (obj)=> {
// scrollHeight 元素内容的高度,包括溢出的不可见内容, 可用来判断多行文本的实际高度
// scrollWidth 元素内容的宽度,包括溢出的不可见内容, 可用来判断单行文本的实际宽度 scrollWidth > clientWidth
// clientWidth
// console.log("clientWidth", obj.target.scrollHeight, obj.target.clientHeight, )
hasShowTips.value = obj.target.scrollHeight > obj.target.clientHeight
width.value = obj.target.clientWidth
}
</script>
五、使用
<template #desc="{ row }">
<overflow-toolTip :content="row.desc" />
</template>
六、总结
因为需要拿到容器的实际高度(obj.target.scrollHeight)和指定高度(obj.target.clientHeight),需要在 dom 渲染完。故在鼠标移入该容器时计算,比较容器的实际高度和指定高度:
(1)如果前者大于后者即文本内容高度超过指定高度,需要实现鼠标移入展示气泡显示所有内容,三点是通过 style 样式实现;
(2)否则即前者小于等于后者,则无需展示气泡和三点;
.text-row {
/* 单行文本溢出三点 */
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.text-row-2 {
/* 多行文本溢出三点 */
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}