Calculate text width with JavaScript

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

    Building off of Deepak Nadar's answer, I changed the functions parameter's to accept text and font styles. You do not need to reference an element. Also, the fontOptions have defaults, so you to not need to supply all of them.

    (function($) {
      $.format = function(format) {
        return (function(format, args) {
          return format.replace(/{(\d+)}/g, function(val, pos) {
            return typeof args[pos] !== 'undefined' ? args[pos] : val;
          });
        }(format, [].slice.call(arguments, 1)));
      };
      $.measureText = function(html, fontOptions) {
        fontOptions = $.extend({
          fontSize: '1em',
          fontStyle: 'normal',
          fontWeight: 'normal',
          fontFamily: 'arial'
        }, fontOptions);
        var $el = $('
    ', { html: html, css: { position: 'absolute', left: -1000, top: -1000, display: 'none' } }).appendTo('body'); $(fontOptions).each(function(index, option) { $el.css(option, fontOptions[option]); }); var h = $el.outerHeight(), w = $el.outerWidth(); $el.remove(); return { height: h, width: w }; }; }(jQuery)); var dimensions = $.measureText("Hello World!", { fontWeight: 'bold', fontFamily: 'arial' }); // Font Dimensions: 94px x 18px $('body').append('

    ').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height));

提交回复
热议问题