vue3 自定义指令 超长自动显示tooltip v-overflow-tooltip

import { h, render } from 'vue';
import { ElTooltip } from 'element-plus';

//测量子节点长度(必须在mounted之后)
export function range(el: HTMLElement) {
    const range = document.createRange();
    range.setStart(el, 0);
    range.setEnd(el, el.childNodes.length);
    return range.getBoundingClientRect().width;
}

//是否超长(必须在mounted之后)
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;
    //el.childNodes是一个动态的数组,删除元素会改变数组的长度,用for会出问题
    while (el.childNodes.length) {
        el.removeChild(el.childNodes[0]);
    }
    // jsx 写法
    // const tooltip = <ElTooltip content={bind.value || text}>{text}</ElTooltip>;
    // vNode写法
    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.directive('overflowTooltip', {
//     mounted: overflowTooltip,
//     updated: overflowTooltip
// });

app.mount('#app');
<template>
    <!--  自定义指令不建议使用在组件上  -->
    <div style="width: 100px;" v-overflow-tooltip>这是一段很长的文字。。。。。。。。。。。。</div>
    <div style="width: 100px;" v-overflow-tooltip="'这里可以修改tooltip的内容,默认是innerText'">这是一段很长的文字。。。。。。。。。。。。</div>
</template>
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值