根据字符串长度和字体大小,动态获取字符串的宽度和高度

/**
 * 获取字符串的显示宽度/高度
 * @param {} text //字符串
 * @param {} fontsize //字符串
 */
export function textWidth(text, fontsize) {
  var span = document.createElement('span')
  var result = {}
  result.width = span.offsetWidth
  result.height = span.offsetHeight
  span.style.visibility = 'hidden'
  if (fontsize) {
    span.style.fontSize = fontsize
  } else {
    span.style.fontSize = '12px'
  }
  // span.style.fontFamily = fontFamily
  span.style.display = 'inline-block'
  document.body.appendChild(span)
  if (typeof span.textContent !== 'undefined') {
    span.textContent = text
  } else {
    span.innerText = text
  }
  result.width = parseFloat(window.getComputedStyle(span).width) - result.width
  result.height = parseFloat(window.getComputedStyle(span).height) - result.height
  return result
}
posted @ 2021-07-10 14:50  吃不棒的胖胖糖  阅读(423)  评论(0编辑  收藏  举报