Prueba este plugin de jQuery:
// Animates the dimensional changes resulting from altering element contents
// Usage examples:
// $("#myElement").showHtml("new HTML contents");
// $("div").showHtml("new HTML contents", 400);
// $(".className").showHtml("new HTML contents", 400,
// function() {/* on completion */});
(function($)
{
$.fn.showHtml = function(html, speed, callback)
{
return this.each(function()
{
// The element to be modified
var el = $(this);
// Preserve the original values of width and height - they'll need
// to be modified during the animation, but can be restored once
// the animation has completed.
var finish = {width: this.style.width, height: this.style.height};
// The original width and height represented as pixel values.
// These will only be the same as `finish` if this element had its
// dimensions specified explicitly and in pixels. Of course, if that
// was done then this entire routine is pointless, as the dimensions
// won't change when the content is changed.
var cur = {width: el.width()+'px', height: el.height()+'px'};
// Modify the element's contents. Element will resize.
el.html(html);
// Capture the final dimensions of the element
// (with initial style settings still in effect)
var next = {width: el.width()+'px', height: el.height()+'px'};
el .css(cur) // restore initial dimensions
.animate(next, speed, function() // animate to final dimensions
{
el.css(finish); // restore initial style settings
if ($.isFunction(callback)) callback();
});
});
};
})(jQuery);
comentarista RonLugge señala que esto puede causar problemas si se llama dos veces en el mismo elemento (s), en donde la primera animación no ha terminado antes de que comience la segunda . Esto se debe a que la segunda animación tomará los tamaños actuales (mid-animation) como los valores deseados de "finalización" y procederá a corregirlos como los valores finales (deteniendo efectivamente la animación en lugar de animar hacia el tamaño "natural") ...
la forma más fácil de resolver este es llamar stop()
antes de llamar showHtml()
, y pasando true
para la segunda) parámetro (jumpToEnd:
$(selector).showHtml("new HTML contents")
.stop(true, true)
.showHtml("even newer contents");
esto hará que la primera animación para completar inmediatamente (si todavía está funcionando), antes de comenzar uno nuevo.
¿Cuál es el punto de la variable de finalización? ¿Y cómo es diferente de cur? – ecoffey
@ecoffey: 'finish' contiene los valores iniciales y finales para los estilos' width' y 'height'. Siempre será diferente de 'cur', que representa los estilos necesarios para fijar el elemento en su ancho y alto iniciales; si fueran iguales, entonces las dimensiones del elemento no cambiarían con su contenido, ¡y esta animación sería inútil! – Shog9
debería devolver este. – Matt