jQuery: Colocar puntos suspensivos cuando un texto no cabe en una linea.
agosto 26th, 2010Un pequeño script rápido y muy sencillo que he elaborado para jQuery, que hace lo que el título de esta entrada. Hasta ahora estaba usando uno de los textOverflow que andan por ahí, pero me estaban dando algún problema.
$.fn.ellipsis = function() { return this.each( function() { var tar = $(this), ow, ls, tg, tw=tar.css({"display":"block","white-space":"nowrap"}).width(), ot=tar.html(), pt=ot, alt=tar.text(), ok=false, ct=false, el=' …'; tar.css({"position":"absolute"}); while (!ok) { ow = tar.css({"width":"auto"}).width(); if (ow > tw) { ls = pt.lastIndexOf(" "); tg = (new RegExp( "<[^>]*$", "g" )).test( pt.substr(0, ls) ); if (ls > 0) { pt = pt.substr(0, ls); tar.html( pt + el ); ct=true; } else { tar.html( el ).attr("title", alt); ok=true && !tg; } } else { if (ct) { tar.attr("title", alt); tar.css({"display":"block","width":tw+"px"}); } ok = true; } } tar.css({"position":""}); }); }
Y para usarlo.
$(".textodeunalinea").ellipsis()
Actualización 27-10-2010: Se han hecho algunas correcciones. Y un detalle; se porta un poquito mal cuando hay Html en el texto. Pendiente de corregir.