JS如何判断文本是否超出隐藏

本文介绍了一个基于 Vue 的自定义悬停提示组件,该组件能够根据内容宽度自动显示完整文本作为工具提示,并通过监听内容变化实时更新提示信息。文章详细展示了组件的模板结构、样式设置及逻辑实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组件模板

<template>
  <el-tooltip placement="top" :disabled="!title">
    <div slot="content">{{ title }}</div>
    <span
      ref="overflowTooltip"
      class="overflow-tooltip"
      :style="{ maxWidth: maxWidth }"
    >
      {{ content }}
    </span>
  </el-tooltip>
</template>

组件样式

<style scoped>
.overflow-tooltip {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: inherit;
  vertical-align: middle;
}
</style>

组件逻辑


export default {
  props: {
    content: [String, Number, Boolean],
    maxWidth: {
      type: String
    }
  },
  data() {
    return {
      title: ''
    }
  },
  watch: {
    content() {
      this.$nextTick(this.getContentTitle)
    }
  },
  mounted() {
    this.getContentTitle()
  },
  methods: {
    getContentTitle() {
      const el = this.$refs.overflowTooltip
      const elComputed = document.defaultView.getComputedStyle(el, '')
      const padding =
        parseInt(elComputed.paddingLeft.replace('px', '')) +
        parseInt(elComputed.paddingRight.replace('px', ''))

      const range = document.createRange()
      range.setStart(el, 0)
      range.setEnd(el, el.childNodes.length)
      const rangeWidth = range.getBoundingClientRect().width
      if (
        rangeWidth + padding > el.offsetWidth ||
        el.scrollWidth > el.offsetWidth
      ) {
        this.title = this.content
      }
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值