只需要一个DIV元素便可实现滑动效果,避免了使用JavaScript为元素的动画(IE浏览器下仅支持IE9以上)
HTML代码
<div style="height: 200px; width: 200px; border: 1px solid #ccc;"> <div class="slider" id="slider">这里是内容</div> </div> <button onclick="document.getElementById('slider').classList.toggle('closed');">点击看看</button>
CSS代码
.slider { overflow-y: hidden; max-height: 500px; /* 最大高度 */ background: pink; height: 200px; width: 200px; /* Webkit内核浏览器:Safari and Chrome*/ -webkit-transition-property: all; -webkit-transition-duration: .5s; -webkit-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); /* Mozilla内核浏览器:firefox3.5+*/ -moz-transition-property: all; -moz-transition-duration: .5s; -moz-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); /* Opera*/ -o-transition-property: all; -o-transition-duration: .5s; -o-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); /* IE9*/ -ms-transition-property: all; -ms-transition-duration: .5s; -ms-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); } .slider.closed { max-height: 0; }
demo演示地址:http://www.w3cways.com/example?pid=1166
总结:
1、两个类连写,表示当这个元素同时有这两个类的时候才应用样式。
2、通过动态切换类可以改变应用到元素上的样式。根据层叠规则覆盖原来的样式。当满足某些条件时,动态切换样式规则是常见需求。