Calculate text width with JavaScript

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

    Here's one I whipped together without example. It looks like we are all on the same page.

    String.prototype.width = function(font) {
      var f = font || '12px arial',
          o = $('
    ') .text(this) .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f}) .appendTo($('body')), w = o.width(); o.remove(); return w; }

    Using it is simple: "a string".width()

    **Added white-space: nowrap so strings with width larger than the window width can be calculated.

提交回复
热议问题