Calculate text width with JavaScript

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

    You can also do this with createRange, which is more accurate, than the text cloning technique:

    function getNodeTextWidth(nodeWithText) {
        var textNode = $(nodeWithText).contents().filter(function () {
            return this.nodeType == Node.TEXT_NODE;
        })[0];
        var range = document.createRange();
        range.selectNode(textNode);
        return range.getBoundingClientRect().width;
    }
    

提交回复
热议问题