1. 程式人生 > >CSS3 如何讓height:auto實現transition過渡效果

CSS3 如何讓height:auto實現transition過渡效果

程式碼如下

<body>
	<script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
	<style type="text/css">
		.oh{overflow:hidden;}
		.box{
			max-height:30px;
			transition: max-height 1s;
			-moz-transition: max-height 1s;	/* Firefox 4 */
			-webkit-transition: max-height 1s;	/* Safari 和 Chrome */
			-o-transition: max-height 1s;	/* Opera */
			background:#ccc;
		}
		/* 
			關鍵在於指定一個大於元素在height:auto 時的高度的值,讓元素過渡到一個達不到的height值,
			這樣就模擬了height:auto過渡的效果
			注意max-height不可設定太大,否則效果不明顯
		*/
		.box-h{max-height:120px;}
	</style>
	<script type="text/javascript">
		function boxClick(){
			$(".box").toggleClass("box-h");
		}
	</script>
	<div class="box oh" onclick="boxClick()">
		<div style="padding:5px 0px;">效果</div>
		<div style="padding:5px 0px;">效果</div>
		<div style="padding:5px 0px;">效果</div>
	</div>
</body>