Calculating text width

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

    Here's a function that's better than others posted because

    1. it's shorter
    2. it works when passing an , , or "string".
    3. it's faster for frequent uses because it reuses an existing DOM element.

    Demo: http://jsfiddle.net/philfreo/MqM76/

    // Calculate width of text from DOM element or string. By Phil Freo 
    $.fn.textWidth = function(text, font) {
        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'));
        return $.fn.textWidth.fakeEl.width();
    };
    

提交回复
热议问题