vue3实现文字溢出鼠标移入出现tips提示

129 阅读1分钟
const vShowTips = {
  mounted: (el: HTMLElement): void => {
    const curStyle = window.getComputedStyle(el, '')
    const textSpan = document.createElement('span')
    textSpan.style.fontSize = curStyle.fontSize
    textSpan.style.fontWeight = curStyle.fontWeight
    textSpan.style.fontFamily = curStyle.fontFamily
    document.body.appendChild(textSpan)
    textSpan.innerHTML = el.innerText
    if (textSpan.offsetWidth > el.offsetWidth) {
      el.style.overflow = 'hidden'
      el.style.textOverflow = 'ellipsis'
      el.style.whiteSpace = 'nowrap'
      el.onmouseenter = function (e) {
        const vcTooltipDom = document.createElement('div')
        vcTooltipDom.style.cssText = `
            max-width:400px;
            max-height: 400px;
            overflow: auto;
            position:absolute;
            top:${e.clientY + 10}px;
            left:${e.clientX}px;
            background:rgba(70, 76, 91, 0.9);
            color:#fff;
            border-radius:4px;
            padding:8px 12px;
            display:inline-block;
            font-size:14px;
            box-shadow:0 1px 6px rgba(0, 0, 0, 0.2);
            z-index:19999
          `
        vcTooltipDom.setAttribute('id', 'vc-tooltip')
        document.body.appendChild(vcTooltipDom)
        document.getElementById('vc-tooltip').innerHTML = el.innerText
      }
      el.onmouseleave = function () {
        const vcTooltipDom = document.getElementById('vc-tooltip')
        vcTooltipDom && document.body.removeChild(vcTooltipDom)
      }
    }
    document.body.removeChild(textSpan)
  },
  unmounted: (): void => {
    const vcTooltipDom = document.getElementById('vc-tooltip')
    vcTooltipDom && document.body.removeChild(vcTooltipDom)
  },
}

export default vShowTips
 import vShowTips from './v-showTips'
 app.directive('showTips', vShowTips)