我有一个显示信息列表的div#menu
。这些信息通过ajax进行更改。当它改变时,我想设置从高度A到高度B的过渡动画。
我知道我可以使用.animate({'height': 'something')
,但我不知道如何将所有这些粘合在一起。
我正在使用jQuery。
我该怎么做?
编辑。
ajax调用如下所示:
$.ajax({
url: $(this).data('redraw-event-url'),
dataType: 'script'
})
您可以在屏幕外将新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', ''));
});
}
});
我相信我有一个更干净、更好的容器解决方案:
<div id="menu_container">
<div id="menu">
<p>my content</p>
</div>
</div>
我所做的是将容器的maxHeight和minHeight锁定为div的当前高度。然后更改所述div的内容。最后,我将容器的max和minHeight:"释放"为内部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);
});
});
您需要通过以下几个步骤来完成:
- 首先,将新数据放在一个不同的div中,最好是隐藏或不在dom上
- 其次,算出第二个div有多高
- 通过animate设置第一个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());
});
一个不错的解决方案是在success
回调上呈现div#menu
对象
$.ajax({
url: $(this).data('redraw-event-url'),
dataType: 'script',
success: function(){
$('div#menu').animate({'height': 'something');
}
})
希望这对有帮助