vue3 盒子内容多出部分省略,鼠标放上隐藏

/**
 * 超出部分隐藏文字省略。。。
 * 鼠标放上显示隐藏文字
 * 使用 : 需要溢出隐藏的直接加上指令 v-show-tips 即可
 *使用方法<div v-show-tips >{{ name }}</div>
 *
 */

export default {
    mounted(el, binding) {
        // 获取元素样式
        const style = window.getComputedStyle(el)
        // 创建用于测量的 span 元素
        const textSpan = document.createElement('span')
        Object.assign(textSpan.style, {
            position: 'absolute',
            left: '-9999px',
            fontSize: style.fontSize,
            fontWeight: style.fontWeight,
            fontFamily: style.fontFamily,
            whiteSpace: 'nowrap' // 防止文本换行
        })
        textSpan.textContent = el.textContent || el.innerText
        document.body.appendChild(textSpan)

        // 检查是否需要省略
        if (textSpan.offsetWidth > el.offsetWidth) {
            // 设置省略样式
            el.style.overflow = 'hidden'
            el.style.textOverflow = 'ellipsis'
            el.style.whiteSpace = 'nowrap'

            // 添加鼠标移入事件
            el.addEventListener('mouseenter', () => {
                // 创建 tooltip 元素
                const tooltip = document.createElement('div')
                tooltip.classList.add('tooltip')
                tooltip.textContent = textSpan.textContent

                // 设置 tooltip 样式
                Object.assign(tooltip.style, {
                    position: 'absolute',
                    top: `${el.getBoundingClientRect().top + el.offsetHeight + 10}px`,
                    left: `${el.getBoundingClientRect().left}px`,
                    backgroundColor: 'rgba(0, 0, 0, 0.6)',
                    color: 'white',
                    padding: '10px',
                    borderRadius: '5px',
                    zIndex: '1000',
                    maxWidth: '100%' // 示例值,可以根据需要调整
                })

                // 将 tooltip 添加到 body
                document.body.appendChild(tooltip)

                // 添加鼠标移出事件
                tooltip.addEventListener('mouseleave', () => {
                    document.body.removeChild(tooltip)
                })

                // 同时监听原始元素的移出事件,确保在鼠标直接从原始元素移出时也能移除 tooltip
                el.addEventListener('mouseleave', () => {
                    document.body.removeChild(tooltip)
                })
            })
        }

        // 清理创建的 span 元素
        document.body.removeChild(textSpan)
    },
    unmounted(el) {
        // 清理可能存在的 tooltip 元素(如果有的话)
        const tooltip = document.querySelector('.tooltip')
        if (tooltip && tooltip.parentNode === document.body) {
            document.body.removeChild(tooltip)
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值