Calcular el ancho del texto
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);
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;
};
Aquí hay una función que es mejor que otras publicadas porque
- es más corto
- Funciona al pasar un
<input>
,<span>
o"string"
. - 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();
};
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 .html
tan a la ligera.