Calculate text width with JavaScript

前端 未结 24 1628
陌清茗
陌清茗 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: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'));
    

提交回复
热议问题