Calculating text width

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

    If your trying to do this with text in a select box or if those two arent working try this one instead:

    $.fn.textWidth = function(){
     var calc = '<span style="display:none">' + $(this).text() + '</span>';
     $('body').append(calc);
     var width = $('body').find('span:last').width();
     $('body').find('span:last').remove();
     return width;
    };
    

    or

    function textWidth(text){
     var calc = '<span style="display:none">' + text + '</span>';
     $('body').append(calc);
     var width = $('body').find('span:last').width();
     $('body').find('span:last').remove();
     return width;
    };
    

    if you want to grab the text first

    0 讨论(0)
  • 2020-11-22 03:39

    after chasing a ghost for two days, trying to figure out why the width of a text was incorrect, i realized it was because of white spaces in the text string that would stop the width calculation.

    so, another tip is to check if the whitespaces are causing problems. use

    &nbsp;
    

    non-breaking space and see if that fixes it up.

    the other functions people suggested work well too, but it was the whitespaces causing trouble.

    0 讨论(0)
  • 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('<span id="text-width-calc"></span>');
        var width = $(this).find('#text-width-calc').width();
        $(this).unwrapInner();
        return width;
      }
    });
    
    0 讨论(0)
  • 2020-11-22 03:43

    The textWidth functions provided in the answers and that accept a string as an argument will not account for leading and trailing white spaces (those are not rendered in the dummy container). Also, they will not work if the text contains any html markup (a sub-string <br> won't produce any output and &nbsp; will return the length of one space).

    This is only a problem for the textWidth functions which accept a string, because if a DOM element is given, and .html() is called upon the element, then there is probably no need to fix this for such use case.

    But if, for example, you are calculating the width of the text to dynamically modify the width of an text input element as the user types (my current use case), you'll probably want to replace leading and trailing spaces with &nbsp; and encode the string to html.

    I used philfreo's solution so here is a version of it that fixes this (with comments on additions):

    $.fn.textWidth = function(text, font) {
        if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').appendTo(document.body);
        var htmlText = text || this.val() || this.text();
        htmlText = $.fn.textWidth.fakeEl.text(htmlText).html(); //encode to Html
        htmlText = htmlText.replace(/\s/g, "&nbsp;"); //replace trailing and leading spaces
        $.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font'));
        return $.fn.textWidth.fakeEl.width();
    };
    
    0 讨论(0)
  • 2020-11-22 03:43

    Sometimes you also need to measure additionally height and not only text, but also HTML width. I took @philfreo answer and made it more flexbile and useful:

    function htmlDimensions(html, font) {
      if (!htmlDimensions.dummyEl) {
        htmlDimensions.dummyEl = $('<div>').hide().appendTo(document.body);
      }
      htmlDimensions.dummyEl.html(html).css('font', font);
      return {
        height: htmlDimensions.dummyEl.height(),
        width: htmlDimensions.dummyEl.width()
      };
    }
    
    0 讨论(0)
  • 2020-11-22 03:45

    This worked better for me:

    $.fn.textWidth = function(){
      var html_org = $(this).html();
      var html_calc = '<span>' + html_org + '</span>';
      $(this).html(html_calc);
      var width = $(this).find('span:first').width();
      $(this).html(html_org);
      return width;
    };
    
    0 讨论(0)
提交回复
热议问题