需求
期望实现一个类似el-table效果的tooltips组件
element ui 组件库中 table-column 组件有一个 show-overflow-tooltip 属性,设置了这个属性后,当表格的单元格宽度不够时单元格内的文本内容会被截断同时在末尾增加一个省略号
问题分解
- 如何实现单行文本超出显示省略号
- 如何动态判断是否需要添加tooltips
实现参考
element table组件的show-overflow-tooltip属性的实现原理
代码
<template>
<div :id="id" class="overflow-tooltip" :title="title" :style="{maxWidth:maxWidth}">
{{ content }}
</div>
</template>
<script>
export default {
props: {
content: [String, Number, Boolean],
maxWidth: {
type: String
}
},
data() {
return {
title: '',
id: Math.random().toString(36).slice(2)
}
},
mounted() {
const el = document.getElementById(this.id)
const elComputed = document.defaultView.getComputedStyle(el, '')
const padding =
parseInt(elComputed.paddingLeft.replace('px', '')) +
parseInt(elComputed.paddingRight.replace('px', ''))
const range = document.createRange()
range.setStart(el, 0)
range.setEnd(el, el.childNodes.length)
const rangeWidth = range.getBoundingClientRect().width
if (
rangeWidth + padding > el.offsetWidth ||
el.scrollWidth > el.offsetWidth
) {
this.title = this.content
}
}
}
</script>
<style scoped>
.overflow-tooltip {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
line-height: 1;
vertical-align: middle;
}
</style>
更简单方式:
对比元素的offsetWidth和scrollWidth是否一致,如果一致说明没有省略号,否则说明有省略号。有省略号就要设置title,否则无需设置title
el-table表头实现省略号
效果
代码
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" width="180" :show-overflow-tooltip="true">
<template slot="header" slot-scope="scope">
<div class="customHeader">
日期fjalskdjf发生了雕刻技法楼上看风景案例
</div>
</template>
</el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
<el-table-column prop="address" label="地址"> </el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: "2016-05-02:上海市普陀区金沙江路 1518 弄",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
{
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
],
};
},
};
</script>
<style lang="scss" scoped>
.customHeader {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>