将字符串放入一个js创建的dom中,设置字符串的文字大小,然后通过offsetWidth获取到宽度,获取成功后将dom销毁
高度获取同理
function getTextWidth(text, fontSize) {
// 创建临时元素
const _span = document.createElement('span')
// 放入文本
_span.innerText = text
// 设置文字大小
_span.style.fontSize = fontSize + 'px'
// span元素转块级
_span.style.position = 'absolute'
// span放入body中
document.body.appendChild(_span)
// 获取span的宽度
let width = _span.offsetWidth
// 从body中删除该span
document.body.removeChild(_span)
// 返回span宽度
return width
}
function getTextHeight(text, fontSize) {
// 创建临时元素
const _span = document.createElement('span')
// 放入文本
_span.innerText = text
// 设置文字大小
_span.style.fontSize = fontSize + 'px'
// span元素转块级
_span.style.position = 'absolute'
// span放入body中
document.body.appendChild(_span)
// 获取span的宽度
let height = _span.offsetHeight
// 从body中删除该span
document.body.removeChild(_span)
// 返回span宽度
return height
}