有没有一种方法可以根据宽度截断字符串?

时间:2020-04-07 10:23:54

标签: javascript jquery arrays html-table truncate

我有一个带有哈希列的表。 我想截断哈希,从开始到结束只看到很少 我用过这个

elem.replace(elem.substring(10, elem.length - 10),'...')

要从开始处仅看到10个,从结束处仅看到10个

但是在桌子上却显示出Z效果

enter image description here

所以我想根据文本的宽度截断 我将通过下一个功能获得

String.prototype.width = function (font) {
  var f = font || '14px Rubik',
    o = $('<div></div>')
      .text(this)
      .css({
        position: 'absolute',
        float: 'left',
        'white-space': 'nowrap',
        visibility: 'hidden',
        font: f
      })
      .appendTo($('body')),
    w = o.width()

  o.remove()

  return w
}

我需要一个函数来截断字符串,直到全部相同为止 诸如此类,但我需要有关此功能或更好的主意的帮助。

function smartTruncate(elem) {
  const baseWidth = 160
  let elemWidth = elem.width()

  for (let i = 0; i < elem.length; i++) {
    if (elemWidth > baseWidth) {

    }
  }
}

谢谢!

0 个答案:

没有答案