这个问题有点老了,但这是我使用基本 jQuery 解决它的方法,以防其他人需要一个简单的解决方案。
在我的例子中,我有一个博客文章列表,这些文章首先呈现到带有 max-height 的页面,它只显示前 4 行文本,其余的是 overflow: hidden。我有一个展开/折叠按钮,可以将文章从折叠形式切换到展开(完全显示)然后再返回。
起初我尝试直接为 max-height 属性设置动画,正如您在上面发现的那样,这不起作用。我也尝试过使用 css 转换,结果同样令人失望。
我也尝试将它设置为一个非常大的数字,例如“1000em”,但这使得动画看起来很愚蠢,因为它实际上是插值到如此大的值(如您所料)。
我的解决方案使用scrollHeight,它用于确定页面加载后每个故事的自然高度,如下所示:
$(function(){ // DOM LOADED
// For each story, determine its natural height and store it as data.
// This is encapsulated into a self-executing function to isolate the
// variables from other things in my script.
(function(){
// First I grab the collapsed height that was set in the css for later use
var collapsedHeight = $('article .story').css('maxHeight');
// Now for each story, grab the scrollHeight property and store it as data 'natural'
$('article .story').each(function(){
var $this = $(this);
$this.data('natural', $this[0].scrollHeight);
});
// Now, set-up the handler for the toggle buttons
$('.expand').bind('click', function(){
var $story = $(this).parent().siblings('.story').eq(0),
duration = 250; // animation duration
// I use a class 'expanded' as a flag to know what state it is in,
// and to make style changes, as required.
if ($story.hasClass('expanded')) {
// If it is already expanded, then collapse it using the css figure as
// collected above and remove the expanded class
$story.animate({'maxHeight': collapsedHeight}, duration);
$story.removeClass('expanded');
}
else {
// If it is not expanded now, then animate the max-height to the natural
// height as stored in data, then add the 'expanded' class
$story.animate({'maxHeight': $story.data('natural')}, duration);
$story.addClass('expanded');
}
});
})(); // end anonymous, self-executing function
});
要对图像执行相同操作,我只需将它们包装在一个外部 div 中,这就是您将设置 max-height 和 overflow:hidden 的内容,就像我在上面使用 div.story 一样。