方法一:元素加载
function getStringWidth(text){
const div = document.createElement('div')
div.innerText = text
div.style.fontSize = `${defaultFontSize}px`
div.style.whiteSpace = 'nowrap'
div.style.position = 'absolute'
document.body.appendChild(div)
const width = div.offsetWidth
div.remove()
return width
}
方法二:canvas预测量
function getStringWidth(text){
const ctx = document.createElement('canvas').getContext('2d')
ctx.font = 'font-size font-family'
const { width } = ctx.measureText(text)
return width
}