通过js动态获取内容块高度结合CSS动画,实现div内容块缓慢展开/收起效果
HTML部分:
<template>
<div>
<h1>Test</h1>
<div class="box">
<el-button type="primary" @click="handleChange">打开</el-button>
<div class="tab-content" ref="stateDom">
<div class="tab-content-box">
<p>Vue3</p>
<p>Vite</p>
<p>TypeScript</p>
<p>Scss</p>
</div>
</div>
</div>
</div>
</template>
JS部分:
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
export default defineComponent({
setup() {
const stateDom = ref(null);
const handleChange = () => {
if (stateDom.value.style.maxHeight) {
stateDom.value.style.maxHeight = null;
} else {
stateDom.value.style.maxHeight = stateDom.value.scrollHeight + "px";
}
};
return {
stateDom,
handleChange,
};
},
});
</script>
CSS部分:
<style lang='scss' scoped>
.tab-content {
margin: 0 auto;
width: 200px;
background: #f2f6fc;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(109, 75, 75, 0.04);
max-height: 0;
overflow: hidden;
transition: max-height 1s ease-out;
.tab-content-box {
padding: 20px;
}
}
</style>