返回列表

字符串根据长度限制自动截断 hui.measureString

默认分类 2019/10/21 10:19

代码如下:

  var hui = {}
  hui.measureString = function (width, str, endFixed) {
    if (str === undefined) str = ''
    else str = String(str)
    var item = document.getElementById('textWidthMeasure')
    if (!item) {
      item = document.createElement('span')
      item.id = 'textWidthMeasure'
      item.style.position = 'absolute'
      item.style.zIndex = -1
      item.style.top = '-100px'
      document.body.appendChild(item)
    }
    var i, len
    for (i = 1, len = str.length + 1; i < len; i++) {
      item.innerText = str.substr(0, i)
      if (item.offsetWidth > width) {
        i--
        break;
      }
    }
    var result = str.substr(0, i)
    if (str.length > i) result = result + (endFixed || '')
    return result
  }
  hui.measureString(200, 'This is a string length auto measure function', '...')


>> 留言评论