2012-02-06 84 views
5

我有一个显示信息列表的div#menu。该信息通过ajax更改。当它发生变化时,我想让动画从高度A转换到高度B.当div的高度发生变化时动画变化

我知道我可以使用.animate({'height': 'something')但我不知道如何将所有这些粘合在一起。

我正在使用jQuery。

我该怎么做?

编辑。

AJAX调用看起来是这样的:

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

您使用哪种方法进行ajax请求? – 2012-02-06 17:44:21

+0

@DanieleB:添加 – Nerian 2012-02-06 17:45:57

回答

7

您可以将新的HTML添加到DOM关屏,使用户无法看到它。然后获取它的高度,并在将新HTML从临时屏幕外位置移动到最终目的地之前更改容器的高度。事情是这样的:

$.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

你需要做的几个步骤:

  • 首先,把新的数据不同的DIV,最好藏在里面,甚至没有了DOM。
  • 其次,弄清楚这第二个div是多高
  • 设置通过动画的第一个div的高度,一旦动画完成,更换内容

这样一些代码:

// 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

哇,代码格式化失败了吗?编辑:它似乎你不能直接放在项目符号列表后面 – Mala 2012-02-06 17:50:05

0

一个很好的解决方案是使在success回调div#menu对象

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

希望这有助于

1

我相信我有一个更清洁,更好的解决方案涉及货柜:

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

我要做的是,我将容器锁定的maxHeight和了minHeight到的当前高度DIV。然后我改变了div的内容。最后,我“释放”容器的最大和最小高度到当前内部div的高度:

$("#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); 
    }); 
});