这是我的解决方案:http: //jsfiddle.net/NHRzH/12/
CSS:
#myDiv {
overflow: hidden;
height: 50px;
}
jQuery:
$("button").click(function(e) {
toggleDiv($(this).attr('href'));
e.preventDefault();
});
function toggleDiv(selector) {
var $this = $(selector);
//Close div, if open.
if($this.hasClass('open'))
{
var originalHeight = $this.data('height');
$this.animate({
height: originalHeight},
200,
function() { $(this).removeClass('open'); });
return false;
}
//Open the div
var currentHeight = $this.height();
autoHeight = $this.css('height', 'auto').height()
$this.data('height', currentHeight)
.height(currentHeight).animate({
height: autoHeight},
200,
function() { $(this).addClass('open'); });
}
HTML:
<div id="myDiv">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>
<button href="#myDiv">Show more</button>
<hr />
<div id="myDiv2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>
<button href="#myDiv2">Show more</button>
这个怎么运作。
我们为按钮分配一个href
值,然后将其传递给一个toggleDiv
函数(处理 div 的切换)。
该toggleDiv
函数将处理 的状态div
,并根据其当前状态将其切换为打开或关闭。它将从中高到全高(自动)。
完整的工作示例可以在这里查看,有多个 div:http: //jsfiddle.net/NHRzH/12/