html实现折叠⾯板,js轻松实现折叠⾯板
移动端导航栏有个很常见的折叠菜单,bootstrap有collapse插件实现,jQuery UI有Accordion组件。最近⽤js⽆插件实现⼀个这样的效果。
探究历程
display:none;
直接采⽤display,虽然实现了控制容器的显⽰和隐藏,但是效果⽣硬。
//jq或者zepeto的hide和show⽅法就是采⽤这个属性
$('#el').hide();
$('#el').show();
/**
show: function() {
return this.each(function() {
//清除元素的内联display="none"的样式
this.style.display == "none" && (this.style.display = null)
//当样式表⾥的该元素的display样式为none时,设置它的display为默认值
if (getComputedStyle(this, '').getPropertyValue("display") == "none") this.style.display = deName)
//defaultDisplay是获取元素默认display的⽅法
})
},
hide: function() {
return this.css("display", "none")js导航栏下拉菜单
}
**/
transition: height 600ms;
改变容器的⾼度,配合overflow: hidden;实现平滑动画
//思路⽰例
//css
.box {
height: 0px;
transition: height 600ms;
overflow: hidden;
background: #4b504c;
}
//html
/
/js
function openAndClose(){
var el = ElementById("box");
ComputedStyle(el).height == "0px"){
el.style.height = "300px";
}else{
el.style.height="0px";
}
}
//这样虽然实现了效果,但是需要提前知道容器的⾼度
//如果设置height为auto,然⽽transition并没有效果
transition: max-height 600ms;
将transition的属性换成max-height,max-height会限制元素的height⼩于这个值,所以我们将关闭状态的值设成0,打开状态设置成⾜够⼤
//思路⽰例
//css
.box {
height: 300px;
max-height: 0px;
transition: max-height 600ms;
overflow: hidden;
background: #4b504c;
}
//html
...
...
//js
function openAndClose(){
var el = ElementById("box");
ComputedStyle(el).maxHeight == "0px"){
el.style.maxHeight = "1040px";
}else{
el.style.maxHeight="0px";
//这样过程中就会有个不尽⼈意的地⽅,关闭的时候总会有点延迟
/
/原因可能是maxHeight到height这个值得过渡过程耗费了时间
//思路:取消transition==》设置height:auto==》
//获取容器真实height==》设置height:0==》
//设置transition==》触发浏览器重排==》
//设置容器真实height
function openAndClose(){
var el = ElementById("box");
ComputedStyle(el).height == "0px"){
// mac Safari下,貌似auto也会触发transition, 故要none下~
ansition = "none";
el.style.height = "auto";
var targetHeight = ComputedStyle(el).height;
ansition = "height 600ms"
el.style.height = "0px";
el.offsetWidth;//触发浏览器重排
el.style.height = targetHeight;
}else{
el.style.height="0px";
}
}
其他
getComputedStyle() ⽅法获取的是最终应⽤在元素上的所有CSS属性对象|MDN