vue、element-ui使用el-tooltip判断文本是否溢出

1.需求:需要实现文本单行显示,超出时,使用省略号,划过该文本时使用tooltip显示全部文本。需要考虑数据是由接口动态获取,只有溢出文本鼠标滑过时显示全部文本,没有溢出的则不需要。

2.实现:

第一步:首先要判断文本是否溢出

这里网上可以找到很多方法,我是用scrollWidth去拿到实际文本长度,跟clientWidth文本可视宽度作比较。需要注意的是我遇到了一个问题,即

判断文本溢出之前一定要使用单行文件溢出显示省略号的css,并且要加在tooltip内部要溢出隐藏的span上,不然scrollWidth和clientWidth会一直为0

 onMouseOver(event) {
      const ev = event.target;
      const evWeight = ev.scrollWidth;
      const contentWidth = ev.clientWidth;
      if (evWeight > contentWidth) {
        this.isShowTooltip = false;
      } else {
        this.isShowTooltip = true;
      }
    },
    
              
                
              
            

补充:(未试)

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

  }
}

你可能感兴趣的:(vue.js,javascript,前端)