Calculate text width with JavaScript

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

    I wrote a little tool for that. Perhaps it's useful to somebody. It works without jQuery.

    https://github.com/schickling/calculate-size

    Usage:

    var size = calculateSize("Hello world!", {
       font: 'Arial',
       fontSize: '12px'
    });
    
    console.log(size.width); // 65
    console.log(size.height); // 14
    

    Fiddle: http://jsfiddle.net/PEvL8/

提交回复
热议问题