Calculating text width

后端 未结 22 1371
轻奢々
轻奢々 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条回答
  •  旧时难觅i
    2020-11-22 03:50

    I modified Nico's code to work for my needs.

    $.fn.textWidth = function(){
        var self = $(this),
            children = self.contents(),
            calculator = $(''),
            width;
    
        children.wrap(calculator);
        width = children.parent().width(); // parent = the calculator wrapper
        children.unwrap();
        return width;
    };
    

    I'm using .contents() as .children() does not return text nodes which I needed. I also found that the returned width was impacted by the viewport width which was causing wrapping so I'm using white-space:nowrap; to get the correct width regardless of viewport width.

提交回复
热议问题