Calcular el ancho del texto

Resuelto Dom asked hace 15 años • 22 respuestas

Estoy intentando calcular el ancho del texto usando jQuery. No estoy seguro de qué, pero definitivamente estoy haciendo algo mal.

Entonces, aquí está el código:

var c = $('.calltoaction');

var cTxt = c.text();

var cWidth =  cTxt.outerWidth();

c.css('width' , cWidth);
Dom avatar Oct 17 '09 23:10 Dom
Aceptado

Esto funcionó mejor para mí:

$.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;
};
Rune Kaagaard avatar May 05 '2010 08:05 Rune Kaagaard

Aquí hay una función que es mejor que otras publicadas porque

  1. es más corto
  2. Funciona al pasar un <input>, <span>o "string".
  3. es más rápido para usos frecuentes porque reutiliza un elemento DOM existente.

Demostración: http://jsfiddle.net/philfreo/MqM76/

// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};
philfreo avatar Mar 08 '2013 19:03 philfreo

Mi solución

$.fn.textWidth = function(){
    var self = $(this),
        children = self.children(),
        calculator = $('<span style="display: inline-block;" />'),
        width;

    children.wrap(calculator);
    width = children.parent().width(); // parent = the calculator wrapper
    children.unwrap();
    return width;
};

Básicamente una mejora con respecto a Rune, que no se usa .htmltan a la ligera.

bevacqua avatar Feb 23 '2013 13:02 bevacqua