String.prototype.getWidth = function (fontSize) { var span = document.getElementById("_getwidthID"); if (span == null) { span = document.createElement("span"); span.id = "_getwidthID"; span.style.visibility = "hidden"; span.style.whiteSpace = "nowrap" } else { span.style.display = "inline-block" } span.innerText = this; span.style.fontSize = fontSize + "px"; var fontWidth = span.offsetWidth; span.style.display = "none"; return fontWidth; }
var str=“测试”;
str.getWidth(12);