import { h, render } from 'vue';
import { ElTooltip } from 'element-plus';
export function range(el: HTMLElement) {
const range = document.createRange();
range.setStart(el, 0);
range.setEnd(el, el.childNodes.length);
return range.getBoundingClientRect().width;
}
export function isOverflow(el: HTMLElement) {
const targetW = el.getBoundingClientRect().width;
return range(el) > targetW;
}
function overflowTooltip(el: HTMLElement, bind: any) {
el.style.overflow = 'hidden';
el.style.textOverflow = 'ellipsis';
el.style.whiteSpace = 'nowrap';
if (!isOverflow(el)) return;
const text = el.innerText;
while (el.childNodes.length) {
el.removeChild(el.childNodes[0]);
}
const tooltip = h(ElTooltip, { content: bind.value || text }, [h('text', text)]);
render(tooltip, el);
const child = el.children[0] as HTMLElement;
const style = child.style;
style.display = 'block';
style.width = '100%';
style.overflow = 'hidden';
style.textOverflow = 'ellipsis';
style.whiteSpace = 'nowrap';
}
const app = createApp(App);
app.directive('overflowTooltip', overflowTooltip);
app.mount('#app');
<template>
<div style="width: 100px;" v-overflow-tooltip>这是一段很长的文字。。。。。。。。。。。。</div>
<div style="width: 100px;" v-overflow-tooltip="'这里可以修改tooltip的内容,默认是innerText'">这是一段很长的文字。。。。。。。。。。。。</div>
</template>