Calculate text width with JavaScript

前端 未结 24 1673
陌清茗
陌清茗 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:45

    This works for me...

    // Handy JavaScript to measure the size taken to render the supplied text;
    // you can supply additional style information too if you have it.
    
    function measureText(pText, pFontSize, pStyle) {
        var lDiv = document.createElement('div');
    
        document.body.appendChild(lDiv);
    
        if (pStyle != null) {
            lDiv.style = pStyle;
        }
        lDiv.style.fontSize = "" + pFontSize + "px";
        lDiv.style.position = "absolute";
        lDiv.style.left = -1000;
        lDiv.style.top = -1000;
    
        lDiv.innerHTML = pText;
    
        var lResult = {
            width: lDiv.clientWidth,
            height: lDiv.clientHeight
        };
    
        document.body.removeChild(lDiv);
        lDiv = null;
    
        return lResult;
    }
    

提交回复
热议问题