2012-02-06 10 views
5

Tengo un div#menu que muestra una lista de información. Esa información cambia a través de ajax. Cuando cambia, quiero animar esa transición de la altura A a la altura B.Animar el cambio de altura de un div cuando su contenido cambia

Sé que puedo usar .animate({'height': 'something') pero no sé cómo pegar todo esto.

Estoy usando jQuery.

¿Cómo puedo hacer eso?

Editar.

La llamada AJAX se ve así:

$.ajax({ 
    url: $(this).data('redraw-event-url'), 
    dataType: 'script' 
    }) 
+0

¿Qué método está utilizando para la solicitud de AJAX? –

+0

@DanieleB: se agregó – Nerian

Respuesta

7

Puedes añadir el nuevo HTML para el DOM fuera de la pantalla para que el usuario no puede verlo. Luego, obtenga su altura y cambie la altura del contenedor justo antes de mover el nuevo HTML de la ubicación temporal fuera de pantalla a su destino final. Algo como esto:

$.ajax({ 
    success : function (serverResponse) { 

     //add the new HTML to the DOM off-screen, then get the height of the new element 
     var $newHTML = $('<div style="position : absolute; left : -9999px;">' + serverResponse + '</div>').appendTo('body'), 
      theHeight = $newHTML.height(); 

     //now animate the height change for the container element, and when that's done change the HTML to the new serverResponse HTML 
     $('#menu').animate({ height : theHeight }, 500, function() { 

      //notice the `style` attribute of the new HTML is being reset so it's not displayed off-screen anymore 
      $(this).html($newHTML.attr('style', '')); 
     }); 
    } 
}); 
1

Tendrá que hacer esto en un par de pasos:

  • primer lugar, poner los nuevos datos dentro de un div diferente, idealmente oculta o no, incluso en el DOM.
  • En segundo lugar, averiguar cuánto mide esta segunda div es
  • establecer la altura de la primera div través animado, y una vez que la animación es terminado, reemplazar el contenido

por lo que algunos código:

// put the content into a hidden div 
$('#hiddendiv').html(content); 

// get the target height 
var newHeight = $('#hiddendiv').height(); 

// animate height and set content 
$('#menu').animate({'height': newHeight}, function(){ 
    $('#menu').html($('#hiddendiv').html()); 
}); 
+0

whoa ¿Qué pasa con el formato del código? EDITAR: parece que no puedes poner el código directamente después de una lista con viñetas – Mala

0

Una buena solución es hacer que el objeto div#menu en la devolución de llamada success

$.ajax({ 
    url: $(this).data('redraw-event-url'), 
    dataType: 'script', 
    success: function(){ 
     $('div#menu').animate({'height': 'something'); 
     } 
    }) 

esperanza esto ayuda

1

Creo que tengo un limpiador, una mejor solución que implica un contenedor:

<div id="menu_container"> 
    <div id="menu"> 
    <p>my content</p> 
    </div> 
</div> 

Lo que hago es que me encierro maxHeight y minHeight del contenedor a la altura actual del div. Luego cambio el contenido de dicho div. Y finalmente "libero" la altura máxima y mínima del contenedor a la altura actual del div interior:

$("#menu_container").css("min-height", $("#menu").height()); 
$("#menu_container").css("max-height", $("#menu").height()); 
$("#menu").fadeOut(500, function() { 

    //insert here the response from your ajax call 
    var newHtml = serverResponse; 

    $(this).html(newHtml).fadeIn(500, function() { 
     $("#menu_container").animate({minHeight:($("#menu").height())},500); 
     $("#menu_container").animate({maxHeight:($("#menu").height())},500); 
    }); 
}); 
Cuestiones relacionadas