获得当前字符串的宽度

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获得当前字符串的宽度</title>
<script type="text/javascript" src="jquery-min.js"></script>
</head>

<body>
<span id="span" style="font-size:14px">china中国人的奥运</span>

</body>
</html>
<script>
//var str='china中国人的奥运';
function textSize(fontSize, text) {
var span = document.createElement("span");
var result = {};
result.width = span.offsetWidth;
result.height = span.offsetHeight;
span.style.visibility = "hidden";
document.body.appendChild(span);
if (typeof span.textContent != "undefined")
span.textContent = text;
else span.innerText = text;
result.width = span.offsetWidth - result.width;
result.height = span.offsetHeight - result.height;
span.parentNode.removeChild(span);
return result;
}

var size = textSize("14px", "china中国人的奥运");
alert("宽:" + size.width + " 高:" + size.height);
//当前字符串的长度
alert("宽:" + span.offsetWidth + " 高:" + span.offsetHeight);



</script>
原文地址:https://www.cnblogs.com/cx709452428/p/5763597.html