Calculate text width with JavaScript

前端 未结 24 1669
陌清茗
陌清茗 2020-11-21 05:08

I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it\'s not built-in, my only idea is t

24条回答
  •  长发绾君心
    2020-11-21 05:41

    Try this code:

    function GetTextRectToPixels(obj)
    {
    var tmpRect = obj.getBoundingClientRect();
    obj.style.width = "auto"; 
    obj.style.height = "auto"; 
    var Ret = obj.getBoundingClientRect(); 
    obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
    obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px"; 
    return Ret;
    }
    

提交回复
热议问题