Calculate text width with JavaScript

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

    In HTML 5, you can just use the Canvas.measureText method (further explanation here).

    Try this fiddle:

    /**
     * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
     * 
     * @param {String} text The text to be rendered.
     * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
     * 
     * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
     */
    function getTextWidth(text, font) {
        // re-use canvas object for better performance
        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
        var context = canvas.getContext("2d");
        context.font = font;
        var metrics = context.measureText(text);
        return metrics.width;
    }
    
    console.log(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86
    

    This fiddle compares this Canvas method to a variation of Bob Monteverde's DOM-based method, so you can analyze and compare accuracy of the results.

    There are several advantages to this approach, including:

    • More concise and safer than the other (DOM-based) methods because it does not change global state, such as your DOM.
    • Further customization is possible by modifying more canvas text properties, such as textAlign and textBaseline.

    NOTE: When you add the text to your DOM, remember to also take account of padding, margin and border.

    NOTE 2: On some browsers, this method yields sub-pixel accuracy (result is a floating point number), on others it does not (result is only an int). You might want to run Math.floor (or Math.ceil) on the result, to avoid inconsistencies. Since the DOM-based method is never sub-pixel accurate, this method has even higher precision than the other methods here.

    According to this jsperf (thanks to the contributors in comments), the Canvas method and the DOM-based method are about equally fast, if caching is added to the DOM-based method and you are not using Firefox. In Firefox, for some reason, this Canvas method is much much faster than the DOM-based method (as of September 2014).

    0 讨论(0)
  • 2020-11-21 05:29

    Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.

    var fontSize = 12;
    var test = document.getElementById("Test");
    test.style.fontSize = fontSize;
    var height = (test.clientHeight + 1) + "px";
    var width = (test.clientWidth + 1) + "px"
    
    console.log(height, width);
    #Test
    {
        position: absolute;
        visibility: hidden;
        height: auto;
        width: auto;
        white-space: nowrap; /* Thanks to Herb Caudill comment */
    }
    <div id="Test">
        abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    </div>

    0 讨论(0)
  • 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) {
        ...
    }
    
    0 讨论(0)
  • 2020-11-21 05:31

    The width and heigth of a text can be obtained with clientWidth and clientHeight

    var element = document.getElementById ("mytext");
    
    var width = element.clientWidth;
    var height = element.clientHeight;
    

    make sure that style position property is set to absolute

    element.style.position = "absolute";
    

    not required to be inside a div, can be inside a p or a span

    0 讨论(0)
  • 2020-11-21 05:31

    I guess this is prety similar to Depak entry, but is based on the work of Louis Lazaris published at an article in impressivewebs page

    (function($){
    
            $.fn.autofit = function() {             
    
                var hiddenDiv = $(document.createElement('div')),
                content = null;
    
                hiddenDiv.css('display','none');
    
                $('body').append(hiddenDiv);
    
                $(this).bind('fit keyup keydown blur update focus',function () {
                    content = $(this).val();
    
                    content = content.replace(/\n/g, '<br>');
                    hiddenDiv.html(content);
    
                    $(this).css('width', hiddenDiv.width());
    
                });
    
                return this;
    
            };
        })(jQuery);
    

    The fit event is used to execute the function call inmediatly after the function is asociated to the control.

    e.g.: $('input').autofit().trigger("fit");

    0 讨论(0)
  • 2020-11-21 05:33
    <span id="text">Text</span>
    
    <script>
    var textWidth = document.getElementById("text").offsetWidth;
    </script>
    

    This should work as long as the <span> tag has no other styles applied to it. offsetWidth will include the width of any borders, horizontal padding, vertical scrollbar width, etc.

    0 讨论(0)
提交回复
热议问题