准确计算字符串的长度
思路:创造一个环境完全一样的容器和文本并计算它的长度.
function textWidth(text) { var span = document.createElement('span'); span.style.visibility = 'hidden'; span.style.fontSize = `${parseFloat( window.getComputedStyle(document.documentElement).fontSize ) * 0.875}px`; span.style.fontFamily = window.getComputedStyle( document.documentElement ).fontFamily; span.style.display = 'inline-block'; span.style.fontWeight = window.getComputedStyle( document.documentElement ).fontWeight; document.body.appendChild(span); if (typeof span.textContent != 'undefined') { span.textContent = text; } else { span.innerText = text; } const width = Math.ceil(parseFloat(window.getComputedStyle(span).width)); return width; }
textWidth(text)