Calculate text width with JavaScript

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

    The Element.getClientRects() method returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client. The returned value is a collection of DOMRect objects, one for each CSS border box associated with the element. Each DOMRect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport.

    Element.getClientRects() by Mozilla Contributors is licensed under CC-BY-SA 2.5.

    Summing up all returned rectangle widths yields the total text width in pixels.

    document.getElementById('in').addEventListener('input', function (event) {
        var span = document.getElementById('text-render')
        span.innerText = event.target.value
        var rects = span.getClientRects()
        var widthSum = 0
        for (var i = 0; i < rects.length; i++) {
            widthSum += rects[i].right - rects[i].left
        }
        document.getElementById('width-sum').value = widthSum
    })
    <p><textarea id='in'></textarea></p>
    <p><span id='text-render'></span></p>
    <p>Sum of all widths: <output id='width-sum'>0</output>px</p>

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

    Building off of Deepak Nadar's answer, I changed the functions parameter's to accept text and font styles. You do not need to reference an element. Also, the fontOptions have defaults, so you to not need to supply all of them.

    (function($) {
      $.format = function(format) {
        return (function(format, args) {
          return format.replace(/{(\d+)}/g, function(val, pos) {
            return typeof args[pos] !== 'undefined' ? args[pos] : val;
          });
        }(format, [].slice.call(arguments, 1)));
      };
      $.measureText = function(html, fontOptions) {
        fontOptions = $.extend({
          fontSize: '1em',
          fontStyle: 'normal',
          fontWeight: 'normal',
          fontFamily: 'arial'
        }, fontOptions);
        var $el = $('<div>', {
          html: html,
          css: {
            position: 'absolute',
            left: -1000,
            top: -1000,
            display: 'none'
          }
        }).appendTo('body');
        $(fontOptions).each(function(index, option) {
          $el.css(option, fontOptions[option]);
        });
        var h = $el.outerHeight(), w = $el.outerWidth();
        $el.remove();
        return { height: h, width: w };
      };
    }(jQuery));
    
    var dimensions = $.measureText("Hello World!", { fontWeight: 'bold', fontFamily: 'arial' });
    
    // Font Dimensions: 94px x 18px
    $('body').append('<p>').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

    Fiddle of working example: http://jsfiddle.net/tdpLdqpo/1/

    HTML:

    <h1 id="test1">
        How wide is this text?
    </h1>
    <div id="result1"></div>
    <hr/>
    <p id="test2">
        How wide is this text?
    </p>
    <div id="result2"></div>
    <hr/>
    <p id="test3">
        How wide is this text?<br/><br/>
        f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi  ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j
    </p>
    <div id="result3"></div>
    

    JavaScript code:

    function getTextWidth(text, font) {
        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;
    };
    
    $("#result1")
    .text("answer: " +
        getTextWidth(
                 $("#test1").text(),
                 $("#test1").css("font")) + " px");
    
    $("#result2")
        .text("answer: " +
            getTextWidth(
                 $("#test2").text(),
                 $("#test2").css("font")) + " px");
    
    $("#result3")
        .text("answer: " +
            getTextWidth(
                 $("#test3").text(),
                 $("#test3").css("font")) + " px");
    
    0 讨论(0)
  • 2020-11-21 05:41

    You can use the canvas so you don't have to deal so much with css properties:

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    ctx.font = "20pt Arial";  // This can be set programmaticly from the element's font-style if desired
    var textWidth = ctx.measureText($("#myElement").text()).width;
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-21 05:41
    var textWidth = (function (el) {
        el.style.position = 'absolute';
        el.style.top = '-1000px';
        document.body.appendChild(el);
    
        return function (text) {
            el.innerHTML = text;
            return el.clientWidth;
        };
    })(document.createElement('div'));
    
    0 讨论(0)
提交回复
热议问题