Calculate text width with JavaScript

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

    The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.

    function textWidth(text, fontProp) {
        var tag = document.createElement("div");
        tag.style.position = "absolute";
        tag.style.left = "-999em";
        tag.style.whiteSpace = "nowrap";
        tag.style.font = fontProp;
        tag.innerHTML = text;
    
        document.body.appendChild(tag);
    
        var result = tag.clientWidth;
    
        document.body.removeChild(tag);
    
        return result;
    }
    

    Usage:

    if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
        ...
    }
    

提交回复
热议问题