Calculate text width with JavaScript

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

    jQuery:

    (function($) {
    
     $.textMetrics = function(el) {
    
      var h = 0, w = 0;
    
      var div = document.createElement('div');
      document.body.appendChild(div);
      $(div).css({
       position: 'absolute',
       left: -1000,
       top: -1000,
       display: 'none'
      });
    
      $(div).html($(el).html());
      var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
      $(styles).each(function() {
       var s = this.toString();
       $(div).css(s, $(el).css(s));
      });
    
      h = $(div).outerHeight();
      w = $(div).outerWidth();
    
      $(div).remove();
    
      var ret = {
       height: h,
       width: w
      };
    
      return ret;
     }
    
    })(jQuery);
    

提交回复
热议问题