React useful code snippets

December 1, 2024

样式计算

  • JS计算文字是否超过元素宽度
/**
 * 判断文字长度是否超过元素宽度
 * element: 可以传入ref.current, 也可以传入一个DOM元素
 * str: 需要计算长度文字
 */
const isTextTruncated = (element: any, str: string) => {
  const computedStyle = window.getComputedStyle(element) // 获取元素计算样式
  const elementWidth = parseFloat(computedStyle.width) // 获取元素宽度
  const fontSize = parseFloat(computedStyle.fontSize) 
  const textWidth = getTextWidth(str, fontSize) // 获取文字宽度
  return textWidth > elementWidth // 判断文字宽度是否超出元素宽度, 如果是, 则触发文字截断逻辑, 比如展示一个Tooltip.
}

/**
 * 通过创建一个div获取文字宽度
 */
const getTextWidth = (text: string, fontSize: number): number => {
    const contentCnt = document.createElement('div') // 创建一个包含文字的div元素
    contentCnt.style.display = 'inline-block'
    contentCnt.style.fontSize = fontSize
    contentCnt.style.visibility = 'hidden'
    contentCnt.style.whiteSpace = 'pre'
    contentCnt.innerText = text
    document.body.appendChild(contentCnt)

    const textWidth = +getComputedStyle(contentCnt).width.replace('px', '')
    document.body.removeChild(contentCnt)
    return textWidth
}