vue中展开与缩放动画,网上大多都是通过监测max-height属性来实现,亲测了一下,有卡顿现象,效果并不理想,最后发现可以通过css+js的方式,通过高度height变化来实现动画。
html代码:
<div class="collapse-item" v-for="(item,index) in linkList" :key="item.name">
<div class="collapse-tab" @click="onTabChange(item,index)">
{{item.name}}
</div>
<div class="collapse-content" ref="collapse_content">
<!--子链接列表-->
<div class="collapse-content-item" v-for="cell in item.children" :key="cell.name">
<a :href="cell.url" :title="cell.name" target="_blank"
>{{ cell.name }}</a>
</div>
</div>
</div>
关键处css样式:
a {
display: inline-block;
color: white;
text-decoration: none;
white-space: nowrap;
padding: 10px 0;
margin-left: 12px;
cursor: pointer;
&:hover {
color: #00ffb6;
}
}
.collapse-content {
display: flex;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
flex-wrap: wrap;
height: 0;//默认是收缩时设置,默认展开不需要设置
transition: height .3s linear;//设置动画
overflow: hidden;
.collapse-content-item {
width: 33%;
font-size: 18px;
text-align: left;
}
}
js相关代码:
默认是收缩状态:
onTabChange(item, index) {
if(tabItem.open == undefined){
tabItem.open = true;
}else{
tabItem.open = !tabItem.open;
}
this.$set(this.linkList,index,tabItem);
//由此网上是为了三角箭头显示效果增加的,在这里不必要
const contentref = this.$refs.collapse_content[index]
let height = contentref.offsetHeight;
if (height === 0) { // 由收缩状态展开
contentref.style.height = 'auto';
height = contentref.offsetHeight;
contentref.style.height = '0px';
let f = document.body.offsetHeight // 必加
contentref.style.height = height + 'px';
} else { // 收缩
contentref.style.height = '0px';
}
}
默认是展开状态时:
1.将展开的高度保存到item项中,下次再展开时赋值
onTabChange(item, index) {
if(tabItem.open == undefined){
tabItem.open = true;
}else{
tabItem.open = !tabItem.open;
}
this.$set(this.linkList,index,tabItem);
const contentref = this.$refs.collapse_content[i];
var height = contentref .offsetHeight; //liCon.getBoundingClientRect().height
if(item.open){
contentref .style.height = item.height + 'px';
}else{
item.height = height;
contentref .style.height = height + 'px';
var f = document.body.offsetHeight;
contentref .style.height = '0px';
}
}
2.此方法第一次测试的时候展开无动画,后来又正常了,不知道是不是缓存的问题
const contentref = this.$refs.collapse_content[i];
let height = contentref.offsetHeight;
if (height === 0) { // 展开
contentref.style.height = 'auto';
height = contentref.offsetHeight;
contentref.style.height = 0 + 'px';
let f = document.body.offsetHeight; // 必加,否则展开无动画
contentref.style.height = height + 'px';
} else { // 收缩
contentref.style.height = height + 'px';
var f = document.body.offsetHeight;
contentref.style.height = 0 + 'px';
}
参考资料:点这里