Calculate text width with JavaScript

前端 未结 24 1686
陌清茗
陌清茗 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
    })

    Sum of all widths: 0px

提交回复
热议问题