样式计算
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
}
const getTextWidth = (text: string, fontSize: number): number => {
const contentCnt = document.createElement('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
}