CSS 支持動(dòng)畫的屬性中的 height 屬性如下:
height :yes, as a length, percentage or calc()
即:當(dāng) height 的值是 length沟娱,百分比或 calc() 時(shí)支持 CSS3 過渡拜轨。
所以當(dāng)元素 height : auto 時(shí)绊袋,是不支持 CSS3 動(dòng)畫的。
對(duì)于動(dòng)態(tài)內(nèi)容,元素的高度應(yīng)設(shè)置為 auto扮念。這樣葵蒂,任何增加或減少的元素高度都將自適應(yīng)。但也會(huì)出現(xiàn)另一個(gè)問題:當(dāng)元素的高度設(shè)置為 auto 時(shí)摔敛,CSS transition 將不起作用。
1全封、確定高度的時(shí)候:
改為max-height
2马昙、不確定高度需要使用js來實(shí)現(xiàn)
<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">測(cè)試數(shù)據(jù){{ 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>