Calculating text width

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

    jQuery's width functions can be a bit shady when trying to determine the text width due to inconsistent box models. The sure way would be to inject div inside your element to determine the actual text width:

    $.fn.textWidth = function(){
      var sensor = $('
    ').css({margin: 0, padding: 0}); $(this).append(sensor); var width = sensor.width(); sensor.remove(); return width; };

    To use this mini plugin, simply:

    $('.calltoaction').textWidth();
    

提交回复
热议问题