通过JS动态计算文本高度
我们在做动态网页APP时有时会需要根据不同的文本高度设置不同的height,这就需要动态计算文本的高度了,之前在网上看到过一个方案,但本人亲自试了一下发现有bug,就是会在页面中多创建一个占位的元素,于是我就将这个bug修复了一下,不废话,上代码。对前端感兴趣的小伙伴可以加我QQ:1627889159。
function textSize (fontSize, fontFamily, text) {
var span = document.createElement('span')
var dom = document.createElement('div')
dom.style.width = '100%'
dom.style.height = '10px'
dom.style.overflow = 'hidden'
var result = {}
result.width = span.offsetWidth
result.height = span.offsetHeight
span.style.visibility = 'hidden'
span.style.fontSize = fontSize
span.style.fontFamily = fontFamily
span.style.display = 'inline-block'
dom.appendChild(span)
document.body.appendChild(dom)
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
}