Calculating text width

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

    Slight change to Nico's, since .children() will return an empty set if we're referencing a text element like an h1 or p. So we'll use .contents() instead, and use this instead of $(this) since we're creating a method on a jQuery object.

    $.fn.textWidth = function(){
        var contents = this.contents(),
            wrapper  = '',
            width    = '';
    
        contents.wrapAll(wrapper);
        width = contents.parent().width(); // parent is now the wrapper
        contents.unwrap();
        return width;
        };
    

提交回复
热议问题