Calculating text width

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

    If you are trying to determine the width of a mix of text nodes and elements inside a given element, you need to wrap all the contents with wrapInner(), calculate the width, and then unwrap the contents.

    *Note: You will also need to extend jQuery to add an unwrapInner() function since it is not provided by default.

    $.fn.extend({
      unwrapInner: function(selector) {
          return this.each(function() {
              var t = this,
                  c = $(t).children(selector);
              if (c.length === 1) {
                  c.contents().appendTo(t);
                  c.remove();
              }
          });
      },
      textWidth: function() {
        var self = $(this);
        $(this).wrapInner('');
        var width = $(this).find('#text-width-calc').width();
        $(this).unwrapInner();
        return width;
      }
    });
    

提交回复
热议问题