前提资料
先决条件
在页面需要展示过渡效果时候,很多情况我们会使用transition,而用transition做效果时候,很多情况是跟width/height做搭配的;
但是transition有需要两个必要条件,一个是起点:如开始过渡效果的高度。以及过渡效果结束后的高度。速度等其他非必须的不在本文的讨论范围内,暂时忽略
问题描述
鉴于上述条件,当我们的元素为内联元素时,元素的height为‘’,则无法满足上述条件中的开始过渡效果时的高度,因此,我们经过百度,会得出两种方法。一种是使用max-height,但是应该大部分人都不会感兴趣,所以本文讲述的是使用第二种方法,通过js去获取到高度
解决思路
当元素的dsiaply为内联的时候,高度是不确定,但是会被子元素撑开,这点是我们确定的,所以我们要做的是获取到" 显示高度 “
也就是我们常用的offsetheight属性,具体请百度。由于现在vue比较流行,我也蹭下热度好了,就写一个vue的版本好了
回正题,获取到offsetheigh。你可以理解为是真正的高度,然后我们就相当于有了一个真实高度了(暂时是这样的,如果页面改变,那就再获取一次),接着,我们就去切换他的高度,一下子为0,一下子为‘真实高度’就可以了,当然,必须有transition属性,讲解的差不多了,我就直接上代码
<template>
<div>
<div>this is a vue file called ulTransition.vue;</div>
<hr />
<div class="flex-div">
<div class="div">
<ul ref="ul" class="showall:true">
<li v-for="i in testnum" :key="i">测试数据i</li>
</ul>
</div>
<div>
<button @click="toggle">收缩/放出</button>
</div>
</div>
</div>
</template>
<script>
export default {
namespace: "ulTransition",
data() {
return {
showli: false,
testnum: 0,
ulheight: 0
};
},
mounted() {
this.testnum = Math.ceil(Math.random() * 10 + 10);
console.log(this.testnum);
this.$nextTick(e => {
console.log("开始了!");
this.ulheight = this.$refs.ul.offsetHeight + "px";
this.$refs.ul.style.height = this.ulheight;
});
},
methods: {
toggle() {
if (this.showli) {
this.$refs.ul.style.height = this.ulheight;
} else {
this.$refs.ul.style.height = 0;
}
this.showli = !this.showli;
}
}
};
</script>
<style scoped>
.flex-div {
width: 100%;
display: flex;
}
.flex-div .div {
flex: 1;
text-align: center;
}
li {
width: 100px;
background-color: #999;
margin-top: 1px;
}
ul {
background-color: #f2f2f2;
transition: all 0.5s;
overflow: hidden;
}
</style>
实验结果
日常放了一份在codepen上,随便放的,大家随意看看:codepen的一个简单例子