Calculating text width

后端 未结 22 1686
轻奢々
轻奢々 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:45

    Expanding on @philfreo's answer:

    I've added the ability to check for text-transform, as things like text-transform: uppercase usually tend to make the text wider.

    $.fn.textWidth = function (text, font, transform) {
        if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').hide().appendTo(document.body);
        $.fn.textWidth.fakeEl.text(text || this.val() || this.text())
            .css('font', font || this.css('font'))
            .css('text-transform', transform || this.css('text-transform'));
        return $.fn.textWidth.fakeEl.width();
    };
    

提交回复
热议问题