获取指定文字的显示宽度,适用于一般情况,代码很简单,如下:

    1. function calcTextWidth(txt = "", font = "") {
    2. let span = document.createElement("span");
    3. span.innerText = txt;
    4. span.style.font = font;
    5. span.style.visibility = "hidden";
    6. span.style.whiteSpace = "nowrap";
    7. document.body.appendChild(span);
    8. let width = span.offsetWidth;
    9. document.body.removeChild(span);
    10. return width;
    11. }

    使用时需要注意 font 参数,例如加粗文字的计算用记得用 bold

    效果可以打开控制台测试看看
    image.png

    2021年12月2日