获取指定文字的显示宽度,适用于一般情况,代码很简单,如下:
function calcTextWidth(txt = "", font = "") {
let span = document.createElement("span");
span.innerText = txt;
span.style.font = font;
span.style.visibility = "hidden";
span.style.whiteSpace = "nowrap";
document.body.appendChild(span);
let width = span.offsetWidth;
document.body.removeChild(span);
return width;
}
使用时需要注意 font 参数,例如加粗文字的计算用记得用 bold
效果可以打开控制台测试看看
2021年12月2日