首先
要知道当前元素的宽
将文字放到一个容器中,将容器的样式(主要是有关字体的样式)都设置为当前元素的样式,然后获取容器的宽,也就是文字的宽
如果文字的宽度超过了当前元素的宽度,则给溢出隐藏的css样式 overflow :hidden;text-overflow: ellipsis;white-space: normal
定义鼠标移入展示浮层,浮层中显示全部内容,鼠标移出销毁浮层
代码
mian.js 中定义全局指令
也可以在组件的directives中注册局部指令
Vue.directive('showTips', {
// el {element} 当前元素
componentUpdated (el) {
const curStyle = window.getComputedStyle(el, '') // 获取当前元素的style
const textSpan = document.createElement('span') // 创建一个容器来记录文字的width
// 设置新容器的字体样式,确保与当前需要隐藏的样式相同
textSpan.style.fontSize = curStyle.fontSize
textSpan.style.fontWeight = curStyle.fontWeight
textSpan.style.fontFamily = curStyle.fontFamily
// 将容器插入body,如果不插入,offsetWidth为0
document.body.appendChild(textSpan