el-tooltip 超出宽度显示文字提示,否则隐藏

2,784 阅读1分钟

需求:
设置固定宽度。
文字超出宽度,用...显示。鼠标悬停到文字上,用el-tooltip显示全部文字内容
如果文字未超出宽度,el-tooltip隐藏。
解决方法:

html

<el-tooltip effect="dark"
            :content="contentHover" // 第一步:鼠标悬停后显示的内容
            placement="top-end" 
            :disabled="isShowTooltip"  // 第二步:关闭文字提示功能
>
      <div class='linkTo' @mouseover="onMouseOver(name)"> // 第三步:鼠标移入事件,很关键
           <span :ref='name'>{{name}}</span>// 第四步 绑定ref
      </div>
</el-tooltip>

data

data(){
    return{
        name: '这里是需要展示的所以文字内容'isShowTooltip: false,
        contentHover:  '',
    }
}

methods

methods:{
        onMouseOver(str) { // 内容超出,显示文字提示内容
            const tag = this.$refs[str]
            const parentWidth = tag.parentNode.offsetWidth // 获取元素父级可视宽度
            const contentWidth = tag.offsetWidth // 获取元素可视宽度
            this.isShowTooltip = contentWidth <= parentWidth  
            // 鼠标悬停后显示的内容
            this.contentHover = this.name
        }
}

css

.linkTo {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

本人在这个基础上做了一些变动...

<template>
  <el-tooltip
    ref="tlp"
    :content="text"
    effect="dark"
    popper-class="custom-tooltip"
    :disabled="tooltipFlag"
    :placement="placement"
  >
    <div class="tooltip" @mouseover="onMouseOver('name')">
      <span ref="name">{{ text ? text : "-" }}</span>
    </div>
  </el-tooltip>
</template>

<script>
export default {
  name: "EllipsisTooltip",
  props: {
    text: { type: String, default: "" }, // 字符内容
    placement: { type: String, default: "top" }
  },
  data() {
    return {
      tooltipFlag: false
    };
  },
  methods: {
    onMouseOver(str) {
      const tag = this.$refs[str];
      if (tag) {
        const parentWidth = tag.parentNode.offsetWidth; // 获取元素父级可视宽度
        const contentWidth = tag.offsetWidth; // 获取元素可视宽度
        this.tooltipFlag = contentWidth <= parentWidth;
      }
    }
  }
};
</script>
<style>
.tooltip {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.custom-tooltip {
  max-width: 400px;
  max-height: 400px;
  background-color: #3280fc !important;
}
.custom-tooltip[x-placement^="top"] .popper__arrow {
  border-top-color: #3280fc !important;
}
.custom-tooltip[x-placement^="top"] .popper__arrow::after {
  border-top-color: #3280fc !important;
}
.el-popover {
  padding: 0 !important;
}
</style>

然后在用的地方使用组件

<Tooltip :text="###"></Tooltip>

转自el-tooltip 超出宽度显示文字提示,否则隐藏 - 简书 (jianshu.io)