欢迎光临
我们一直在努力

html中使用js计算字符串所占宽度

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);

赞(0)
版权归原作者所有,如有侵权请告知。达维营-前端网 » html中使用js计算字符串所占宽度

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址