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

相关推荐
云和数据.ChenGuang11 小时前
Component template requires a root element, rather than just错误
前端·javascript·vue.js
mCell11 小时前
为博客添加 RSS 订阅
前端·vitepress·rss
艾小码11 小时前
告别JS初学者噩梦:这样写流程控制和函数才叫优雅
前端·javascript
sdgsdgdsgc13 小时前
Next.js企业级应用开发:SSR、ISR与性能监控方案
开发语言·前端·javascript
哲此一生98413 小时前
搭建Vue3工程(去除不必要的文件)
前端·javascript·vue.js
心止水j14 小时前
spark
javascript·数据库·spark
黑云压城After16 小时前
H5使用环信实现视频或语音通话
前端·javascript·vue.js
未来之窗软件服务18 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法
你的人类朋友19 小时前
什么是断言?
前端·后端·安全
FIN666820 小时前
昂瑞微:实现精准突破,攻坚射频“卡脖子”难题
前端·人工智能·安全·前端框架·信息与通信