创建具有以下样式的DIV。在Javascript中,设置要测量的字体大小和属性,将字符串放入DIV中,然后读取DIV的当前宽度和高度。它将拉伸以适合内容,并且大小将在字符串呈现大小的几个像素之内。
var fontSize = 12;var test = document.getElementById("Test");test.style.fontSize = fontSize;var height = (test.clientHeight + 1) + "px";var width = (test.clientWidth + 1) + "px"console.log(height, width);#Test{ position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; }<div id="Test"> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div>


