【el-tooltips改造】Vue实现文本溢出才显示el-tooltip,否则不显示el-tooltips

实现原理:

使用disabled属性控制el-tooltip的content显示与隐藏;

目标:

1行省略、多行省略、可缩放页面内的文本省略都有效。

实现方式:

1、自定义全局指令,tooltipAutoShow.js代码如下(参考的el-table中的内容超出才显示tooltips的逻辑):

javascript 复制代码
/**
* tooltip-auto-show tooltip不超长则不显示
*/
import Vue from 'vue'
import { getStyle } from 'element-ui/src/utils/dom'
export default {
  inserted(el, binding, vnode) {
    el.__vueOverflowTooltipMouseenter__ = function(e) {
      const defalutSilent = !!Vue.config.silent
      Vue.config.silent = true
      vnode.componentInstance.disabled = true
      const range = document.createRange()
      range.setStart(el, 0)
      range.setEnd(el, el.childNodes.length)
      const rangeWidth = Math.round(range.getBoundingClientRect().width)
      const padding = (parseInt(getStyle(el, 'paddingLeft'), 10) || 0) + (parseInt(getStyle(el, 'paddingRight'), 10) || 0)
      let elWidth = el.offsetWidth
      // 兼容getBoundingClientRect().width值受scale缩放影响
      if (el.offsetWidth < Math.round(el.getBoundingClientRect().width)) {
        elWidth = Math.round(el.getBoundingClientRect().width)
      }
      // 1行省略
      if (rangeWidth + padding > elWidth || el.scrollWidth > elWidth) {
        vnode.componentInstance.disabled = false
      }
      // 处理多行省略
      if (getStyle(el, '-webkit-line-clamp') > 1 && el.scrollHeight > el.offsetHeight) {
        vnode.componentInstance.disabled = false
      }
      Vue.config.silent = defalutSilent
    }
    el.addEventListener('mouseenter', el.__vueOverflowTooltipMouseenter__)
  },
  unbind: function(el) {
    el.removeEventListener('mouseenter', el.__vueOverflowTooltipMouseenter__)
    delete el.__vueOverflowTooltipMouseenter__
  }
}
javascript 复制代码
import tooltipAutoShow from './module/tooltipAutoShow'

Vue.directive('tooltip-auto-show', tooltipAutoShow)

2、使用方式:

html 复制代码
<el-tooltip v-tooltip-auto-show class="" effect="dark" :content="data.name" placement="top-start">
    <div>{{ data.name }}</div>
</el-tooltip>

3、实现效果:

相关推荐
yinuo6 分钟前
前端跨页面通讯终极指南⑥:SharedWorker 用法全解析
前端
PineappleCoder5 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪5 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯5 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
源码获取_wx:Fegn08955 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视5 小时前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan5 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
JIngJaneIL6 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
+VX:Fegn08956 小时前
计算机毕业设计|基于springboot + vue图书管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
阿蒙Amon7 小时前
JavaScript学习笔记:6.表达式和运算符
javascript·笔记·学习