use css3 (transiton) animate element height/width from/to 0 to/from auto

Reference: — 参考


It’s not easy to invent a perfect animation function with css3 transition. Some guys suggests use max-height to animate height from 0 to auto. Well, it’s doable if we just want to animate from 0 to auto and we don’t want perfect control of animation speed. But when we comes to toggling height between zero or some other fixed height, as well as preciously control animating speed, the max-height trick will put you down.
当元素的高度不确定时,使用CSS3的transition属性来制作元素高度动画并不容易。有人建议使用 max-height  属性来做,但这并不理想。因为其一是不能精确控制动画的速度,二是无法回收——就是把高度为auto的,动画切换到高度为0.

So, today, Paul Lan will introduce another option for you.

Before started, one thing I need to mention is repaint mechanism behind browser. We know that, browser will not repaint/redraw its content while executing javascript. So if we change an element style to ‘auto’ and calculate its height/width and then change it back to previous value, browser will not have any change with it’s layout.
这里介绍一个知识先:当Javascript执行时,一般情况下,浏览器是不会重绘其内容的。所以,如果我们把一个元素的高度改变为 auto,又马上改变回之前的旧值,浏览器在视觉上不会发生任何变化。

That’s it! Look at this final code example: