这个问题已经有点老了,但这里是我如何使用基本的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
});
做图像一样,我只想将它们包装在外层这是你将设置max-height
和overflow:hidden
,就像我上面的div.story一样。
有人已经问过并解决了这个问题http://stackoverflow.com/questions/4901643/animate-max-width-on-img-jquery – Craig 2013-01-03 20:31:29