我认为这或多或少是您正在寻找的。诀窍是有两个嵌套的div。外层控制实际高度,内层用于计算自然高度。动画完成后,外部 div 如果展开则恢复为“auto”,以便您可以动态添加更多列表元素。
这是无耻地改编自JQuery 博客文章。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Animate to Auto</title>
<style type="text/css">
.inner {background:#ccc;height:auto;overflow:hidden;}
.inner ol{margin:0;}
.box{height:0px;overflow:hidden;}
</style> <script type="text/javascript" charset="utf-8"
src="http://yui.yahooapis.com/3.2.0/build/yui/yui-min.js">
</script>
</head>
<body>
<button class="btn">Toggle Height</button>
<div class="box">
<div class="inner">
<ol>
<li>Bashful</li>
<li>Doc</li>
<li>Dopey</li>
<li>Grumpy</li>
<li>Happy</li>
<li>Sleepy</li>
<li>Sneezy</li>
</ol>
</div>
</div>
OTHER STUFF HERE
<script>
YUI().use('node', 'event', 'anim', function(Y) {
var heightAnim = new Y.Anim({
node: Y.one('.box'),
to: {
height: 0
}
});
heightAnim.on('end', function (e) {
var box = heightAnim.get('node');
if (parseInt(box.getStyle('height')) > 0) {
box.setStyle('height', 'auto');
}
});
Y.one('.btn').on('click', function(e){
var box = this.get('node');
var inner = box.one('.inner');
var boxH = box.getStyle('height');
if (boxH === 'auto') {
box.setStyle('height',inner.getStyle('height'));
this.set('to', {height: 0});
this.run();
} else {
this.set('to', {height: parseInt(inner.getStyle('height'))});
this.run();
}
},heightAnim);
});
</script>
</body>
</html>