【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、实现效果:

相关推荐
你的人类朋友8 分钟前
说说git的变基
前端·git·后端
姑苏洛言11 分钟前
网页作品惊艳亮相!这个浪浪山小妖怪网站太治愈了!
前端
字节逆旅18 分钟前
nvm 安装pnpm的异常解决
前端·npm
Jerry33 分钟前
Compose 从 View 系统迁移
前端
IT码农-爱吃辣条1 小时前
Three.js 初级教程大全
开发语言·javascript·three.js
GIS之路1 小时前
2025年 两院院士 增选有效候选人名单公布
前端
四岁半儿1 小时前
vue,H5车牌弹框定制键盘包括新能源车牌
前端·vue.js
烛阴1 小时前
告别繁琐的类型注解:TypeScript 类型推断完全指南
前端·javascript·typescript
gnip1 小时前
工程项目中.env 文件原理
前端·javascript
JefferyXZF2 小时前
Next.js Server Actions 详解: 无缝衔接前后端的革命性技术(八)
前端·全栈·next.js