判断文本是否溢出并添加tooltip提示

判断文本是否溢出并添加tooltip提示

1. css控制文本溢出显示省略号

.text-block {
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: keep-all;
}

2. 代码计算文本长度并决定是否显示tooltip

大致的思路:

  1. 计算文本的实际宽度 T
  2. 计算容器的实际宽度 C
  3. 判断是否 T > C,若是,设置 tooltip 元素显示

代码示例(来自ElementUI):

<template>
  <el-tooltip
    class="text-tip-box"
    v-bind="$attrs"
    :disabled="showTip"
    :placement="placement"
  >
    <template #content>
      <span v-if="text || content">{{ text || content }}</span>
      <span v-else><slot></slot></span>
    </template>

    <div class="text-tip-box__text" @mouseenter.stop="onMouseEnter">
      <slot>{{ text }}</slot>
    </div>
  </el-tooltip>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';

interface IProps {
  placement?: string;
  content?: string;
  text?: string;
  lineNumber?: number;
}

const prop = withDefaults(defineProps<IProps>(), {
  placement: 'top',
  lineNumber: 1,
  text: '',
  content: '',
});

const showTip = ref<boolean>(false);

function onMouseEnter(e: MouseEvent) {
  const dom = e.target as HTMLElement;
  if (!dom) {
    return;
  }
  showTip.value = !(
    dom.offsetWidth < dom.scrollWidth || dom.offsetHeight < dom.scrollHeight
  );
}
</script>

<style lang="scss" scoped>
.text-tip-box__text {
  width: 100%;
  word-break: break-all;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  -webkit-line-clamp: v-bind('prop.lineNumber');
}
</style>