已经遇到这种文本长但是能展示的位置很有限需要将文字超出的地方展示为一个省略号 但是鼠标移动上去还需要展示全部的文字 今天编写了一个vue的指令去操作这个问题
import Vue from 'vue'
import { Tooltip } from 'element-ui'
import ResizeObserver from 'resize-observer-polyfill';
const syncVar = (node, binding, vnode, value = 1) => {
let flag
if(value > 1) {
Vue.nextTick(function() {
let style = window.getComputedStyle(node);
let height
if(style.height) {
height = style.height.split('px')[0] * 1
} else {
height = style.fontSize.split('px')[0] * 1.2 * value
}
flag = node.offsetWidth <= node.scrollWidth && height <= node.scrollHeight
if(flag) {
const parent = node.parentNode
const tooltipInstance = new Vue({
render: h => h(Tooltip, {
props: {
content: node.innerText,
placement: binding.arg || 'top',
effect: 'dark'
}
},[
h('p', {
ref: 'content',
class: node.className
}, node.innerHTML)
])
}).$mount()
const wrapper = tooltipInstance.$refs.content
parent.replaceChild(wrapper, node)
}
});
}else {
flag = node.offsetWidth < node.scrollWidth
if(flag) {
const parent = node.parentNode
const tooltipInstance = new Vue({
render: h => h(Tooltip, {
props: {
content: node.innerText,
placement: binding.arg || 'top',
effect: 'dark'
}
},[
h('p', {
ref: 'content',
class: node.className
}, node.innerHTML)
])
}).$mount()
const wrapper = tooltipInstance.$refs.content
parent.replaceChild(wrapper, node)
}
}
}
Vue.directive('ellipsis', {
inserted: function(el, binding, vnode) {
const node = binding.modifiers.parent ? el.parentNode : el
syncVar(node, binding, vnode, binding.value);
const ro = new ResizeObserver((entries, observer) => {
entries[0].target && syncVar(node, binding, vnode, binding.value)
});
ro.observe(node);
},
componentUpdated: function(el, binding, vnode) {
const node = binding.modifiers.parent ? el.parentNode : el
syncVar(node, binding, vnode, binding.value);
}
})
使用方式
1.单行文本
<p v-ellipsis class=" title line1hiden" >{{ title }}</p>
<p v-ellipsis='1' class=" title line1hiden" >{{ title }}</p>
2.两行文本
<p v-ellipsis='2' class=" title line2hiden" >{{ title }}</p>