最近做一个资源共享的需求,要求将资源名称,共享目标人的工号一定要显示出来,也就是文本超长,显示省略点,但是如果使用css,文本超长省略号会在末尾显示,因此利用js截取来实现

//获取字体是为了计算文本所占用的宽度,必须传递一个dom节点,随便选择一个即可,因为系统的字体都是一样的
mounted(){
    // 获取系统字体
    this.getFontFamily(document.getElementById('side-content'))
  },

将获取的字体参数使用全局变量存储起来,供计算文本宽度当成参数使用

    getFontFamily(elem) {
      this.computedStyles = window.getComputedStyle(elem)['font-family']
      console.log(this.computedStyles,'当前系统所用字体')
    },

根据文本内容获取当前截取文字所用的屏幕宽度

    // 获取当前文本所占用的宽度
    getTextWidth(text, font) {
      const canvas = this.getTextWidth.canvas || (this.getTextWidth.canvas = document.createElement("canvas"))
      const context = canvas.getContext("2d")
      context.font = font
      const metrics = context.measureText(text)
      return metrics.width
    },

核心方法,判断文本,逐步截取,当文本宽度超出设定宽度时,截取的当前文字拼接上+'...'+字符串末尾截取 就是完整文本,但是我的工号长度是不一定的,因此利用前一段文本+后一段文本==定宽,这样当工号后面长一些的时候,前面就少截取一部分内容,当工号后面的内容过长,前部分文本就多截取一些

    handleSubstring(arr){  
      let _this = this
      arr.forEach(item=>{
        let str=''
        let newStr = item.targetPath.substring(item.targetPath.lastIndexOf("工号"),item.targetPath.length);
        for (let i = 0; i < item.targetPath.length; i++) {
          if(_this.getTextWidth(str,`normal 14px ${_this.computedStyles}`) + _this.getTextWidth(newStr,`normal 14px ${_this.computedStyles}`)>270){     
             _this.$set(item,'newtargetPath',str+'...'+newStr)
             break
          } else {
            str+=item.targetPath[i]
          }
        }
      })
      console.log(arr,'处理之后的arr数据')
    },

最后看下成果图:

​​​​​​​

 

Logo

前往低代码交流专区

更多推荐