Calculating text width

后端 未结 22 1613
轻奢々
轻奢々 2020-11-22 03:36

I\'m trying to calculate text width using jQuery. I\'m not sure what, but I am definitely doing something wrong.

So, here is the code:

var c = $(\'.c         


        
22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 03:51

    I could not get any of the solutions listed to work 100%, so came up with this hybrid, based on ideas from @chmurson (which was in turn based on @Okamera) and also from @philfreo:

    (function ($)
    {
        var calc;
        $.fn.textWidth = function ()
        {
            // Only create the dummy element once
            calc = calc || $('').css('font', this.css('font')).css({'font-size': this.css('font-size'), display: 'none', 'white-space': 'nowrap' }).appendTo('body');
            var width = calc.html(this.html()).width();
            // Empty out the content until next time - not needed, but cleaner
            calc.empty();
            return width;
        };
    })(jQuery);
    

    Notes:

    • this inside a jQuery extension method is already a jQuery object, so no need for all the extra $(this) that many examples have.
    • It only adds the dummy element to the body once, and reuses it.
    • You should also specify white-space: nowrap, just to ensure that it measures it as a single line (and not line wrap based on other page styling).
    • I could not get this to work using font alone and had to explicitly copy font-size as well. Not sure why yet (still investigating).
    • This does not support input fields that way @philfreo does.

提交回复
热议问题