文字超出显示省略号,移入显示悬浮提示框

创建js文件
export default {
  // el {element} 当前元素
  bind(el, { value }, vnode) {
    const curStyle = window.getComputedStyle(el, ""); // 获取当前元素的style
    const textSpan = document.createElement("span"); // 创建一个容器来记录文字的width
    let num = parseInt(Math.random() * 1000);
    vnode.key = num;
    // 设置新容器的字体样式,确保与当前需要隐藏的样式相同
    textSpan.style.fontSize = curStyle.fontSize;
    textSpan.style.fontWeight = curStyle.fontWeight;
    textSpan.style.fontFamily = curStyle.fontFamily;
    // 将容器插入body,如果不插入,offsetWidth为0
    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:fixed;
          top:${e.clientY + 5}px;
          left:${e.clientX}px;
          background: #000;
          color:#fff;
          border-radius:5px;
          padding:10px;
          display:inline-block;
          font-size:12px;
          z-index:19999
        `;
          // 设置id方便寻找
          vcTooltipDom.setAttribute("id", "vc-tooltip");
          // 将浮层插入到body中
          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);
  }, 
};
src\directive\index.js文件引入
import showTips from './js/showTips';
const directives = {
  showTips
}
export default {
  install(Vue){
    Object.keys(directives).forEach(key=>{
      Vue.directive(key, directives[key])
    })
  }
}
main.js引入
import Directives from "@/directive/index";
Vue.use(Directives);
使用
<p v-showTips style="width:250px">测试长度</p>
此方法有个问题,需要显示省略号的数据是接口调用的,所以一开始加载界面时数据还没出来,文字未超出的时候移入也会显示提示框
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值