js根据长度并计算渲染px width宽度

需求

公司项目需求是要做动态响应式表头,因此就要动态渲染表格表头宽度在一定范围内(100px-200px)。
完整实现图:
image

实现过程

这里就不讲css自动超出省略了,主要是然后根据后台返回的字符串计算实际渲染字符宽度,并设置给 element 表头的 min-width

  :min-width="calcMinWidth(item.displayName)"

核心函数代码:

    calcMinWidth(displayName) {
      // 100 - 200
      // console.log(displayName.length)
      console.log(displayName)
      // 计算文本在页面所占px宽度 -- 扩展String原型方法pxWidth
      String.prototype.pxWidth = function(font) {
        const canvas =
          String.prototype.pxWidth.canvas ||
          (String.prototype.pxWidth.canvas = document.createElement('canvas'))
        const context = canvas.getContext('2d')
        font && (context.font = font)
        const metrics = context.measureText(this)
        return metrics.width
      }
      // 根据需求范围返回
      const width = displayName.pxWidth('bold 18px Lato') + 30
      if (width <= 100) {
        return '100'
      } else if (width >= 200) {
        return '200'
      } else {
        return width + ''
      }
    },

因为我这个是英文项目,没有考虑中文字符,如果存在中文字符还需要特别处理,更多请参考下面的文章。

参考链接

js获取字符长度并计算px宽度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章