准确计算字符串的长度

思路:创造一个环境完全一样的容器和文本并计算它的长度.

function textWidth(text) {
  var span = document.createElement('span');
  span.style.visibility = 'hidden';
  span.style.fontSize = `${parseFloat(
    window.getComputedStyle(document.documentElement).fontSize
  ) * 0.875}px`;
  span.style.fontFamily = window.getComputedStyle(
    document.documentElement
  ).fontFamily;
  span.style.display = 'inline-block';
  span.style.fontWeight = window.getComputedStyle(
    document.documentElement
  ).fontWeight;
  document.body.appendChild(span);
  if (typeof span.textContent != 'undefined') {
    span.textContent = text;
  } else {
    span.innerText = text;
  }

  const width = Math.ceil(parseFloat(window.getComputedStyle(span).width));

  return width;
}

textWidth(text)

  

posted @ 2021-12-22 11:46  一路向北√  阅读(215)  评论(0编辑  收藏  举报

web应用开发&研究 -

业精于勤而荒于嬉。

工作,使我快乐。


Font Awesome | Respond.js | Bootstrap中文网