Pregunta

Entonces, esto podría ser realmente simple, pero aún no he podido encontrar ningún ejemplo del que aprender, así que por favor tengan paciencia conmigo. ;)

Esto es básicamente lo que quiero hacer:

<div>Lots of content! Lots of content! Lots of content! ...</div>

.... 

$("div").html("Itsy-bitsy bit of content!");

Quiero animar suavemente entre las dimensiones del div con mucho contenido a las dimensiones del div con muy poco cuando se inyecta el nuevo contenido.

¿Pensamientos?

¿Fue útil?

Solución

Prueba este complemento 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);

El comentarista RonLugge señala que esto puede causar problemas si lo llama dos veces en el mismo elemento (s), 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 (animación media) como el " final " deseado; los valores, y proceda a corregirlos como los valores finales (deteniendo efectivamente la animación en sus pistas en lugar de animarla hacia el tamaño "natural") ...

La forma más fácil de resolver esto es llamar a stop () antes de llamar a showHtml () , y pasar true para el segundo parámetro ( jumpToEnd ):

$(selector).showHtml("new HTML contents")
           .stop(true, true)
           .showHtml("even newer contents");

Esto hará que la primera animación se complete inmediatamente (si aún se está ejecutando), antes de comenzar una nueva.

Otros consejos

Puede usar el método animado .

$("div").animate({width:"200px"},400);

tal vez algo como esto?

$(".testLink").click(function(event) {
    event.preventDefault();
    $(".testDiv").hide(400,function(event) {
        $(this).html("Itsy-bitsy bit of content!").show(400);
    });
});

Cerca de lo que creo que querías, prueba también slideIn / slideOut o mira el complemento UI / Efectos.

Así es como solucioné esto, ¡espero que esto sea útil! La animación es 100% suave :)

HTML:

<div id="div-1"><div id="div-2">Some content here</div></div>

Javascript:

// cache selectors for better performance
var container = $('#div-1'),
    wrapper = $('#div-2');

// temporarily fix the outer div's width
container.css({width: wrapper.width()});
// fade opacity of inner div - use opacity because we cannot get the width or height of an element with display set to none
wrapper.fadeTo('slow', 0, function(){
    // change the div content
    container.html("<div id=\"2\" style=\"display: none;\">new content (with a new width)</div>");
    // give the outer div the same width as the inner div with a smooth animation
    container.animate({width: wrapper.width()}, function(){
        // show the inner div
        wrapper.fadeTo('slow', 1);
    });
});

Puede que haya una versión más corta de mi código, pero lo mantuve así.

Esto hace el trabajo por mí. También puede agregar un ancho a la división temporal.

$('div#to-transition').wrap( '<div id="tmp"></div>' );
$('div#tmp').css( { height: $('div#to-transition').outerHeight() + 'px' } );
$('div#to-transition').fadeOut('fast', function() {
  $(this).html(new_html);
  $('div#tmp').animate( { height: $(this).outerHeight() + 'px' }, 'fast' );
  $(this).fadeIn('fast', function() {
    $(this).unwrap();
  });
});

Hola meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.

Podría ajustar el 'contenido div' con un 'div externo' que se establece en un valor de ancho absoluto. Inyecte el nuevo contenido con un " hide () " o " animar ({ancho}) " Método, que se muestra en las otras respuestas. De esta manera, la página no fluye en el medio porque el contenedor wrap tiene un ancho constante.

Puede suavizar la animación jQuery usando dequeue . Pruebe la presencia de la clase (establecida al pasar el mouse y eliminada en la devolución de llamada animada mouseOut) antes de mirar una nueva animación. Cuando se inicie una nueva animación, quita la cola.

Aquí hay una demostración rápida.

var space = ($(window).width() - 100);
$('.column').width(space/4);

$(".column").click(function(){
    if (!$(this).hasClass('animated')) {
        $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {});
    }

  $(this).addClass('animated');
    $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {
          $(this).removeClass('animated').dequeue();

      });
    $(this).dequeue().stop().animate({
        width:(space/4)
    }, 1400,'linear',function(){
      $(this).html('AGAIN');
    });
});

La demostración se configura como 5 columnas de altura completa, al hacer clic en cualquiera de las columnas 2 a 5 se animará el ancho de alternancia de las otras 3 y se moverá el elemento en el extremo izquierdo.

ingrese la descripción de la imagen aquí

ingrese la descripción de la imagen aquí

Para incluir la solución del complemento jquery (reputación demasiado baja para agregar esto como un comentario) jQuery.html () eliminará cualquier controlador de eventos en el html adjunto. Cambio:

// Modify the element's contents. Element will resize.
el.html(html);

a

// Modify the element's contents. Element will resize.
el.append(html);

conservará los controladores de eventos del " html " elementos

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top