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

相关推荐
天蓝色的鱼鱼14 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君8799714 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter
进击的尘埃14 小时前
AI 代码审查工具链搭建:用 AST 解析 + LLM 实现自动化 Code Review 的前端工程方案
javascript
juejin_cn14 小时前
[转][译] 从零开始构建 OpenClaw — 第五部分(对话压缩)
javascript
leolee1815 小时前
Redux Toolkit 实战使用指南
前端·react.js·redux
bluceli15 小时前
React Hooks最佳实践:写出优雅高效的组件代码
前端·react.js
IT_陈寒15 小时前
JavaScript代码效率提升50%?这5个优化技巧你必须知道!
前端·人工智能·后端
IT_陈寒15 小时前
Java开发必知的5个性能优化黑科技,提升50%效率不是梦!
前端·人工智能·后端
LDX前端校草15 小时前
前端开发规则配置
前端
代码老中医15 小时前
2026前端工程化新范式:如何用AI驱动你的设计系统?
前端