1、假设盒子里有很多内容,超出了盒子的高度,我们通过给元素增加或删减类名的方式修改他的样式,把他的类名定义动态属性 :class="selClassName" ,
<div :class="selClassName" @click="handleBox">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
2、将类名绑定成一个数组js代码如下:
<script setup lang="ts">
import { ref } from 'vue'
//类名绑定成一个数组
const selClassName = ref(['sel-menu'])
//表记盒子的状态
const selStatus = ref(false)
const handleBox = () => {
//点击按钮如果是展开就折叠
if(selStatus.value) {
selClassName.value.pop()
selStatus.value = false
}else {
selClassName.value.push('expand')
selStatus.value = true
}
}
</script>
3、 css代码如下:
//折叠样式
.sel-menu {
height: 50px;
width: 300px;
border: 1px solid #000;
overflow: hidden;
cursor: pointer;
transition: all 0.2s linear;
position: relative;
.btn {
width: 50px;
height: 30px;
position: absolute;
top: 0;
right: 0;
border: 1px solid red;
line-height: 30px;
text-align: center;
}
div {
width: 200px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
background-color: pink;
margin-bottom: 10px;
}
}
//展开样式
.expand {
height: 360px;
}
完整代码:
<template>
<div class="container" >
<!-- 1假设盒子里有很多内容,超出了盒子的高度 -->
<div :class="selClassName" >
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div class="btn" @click="handleBox">变换</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
//类名绑定成一个数组
const selClassName = ref(['sel-menu'])
//表记盒子的状态
const selStatus = ref(false)
const handleBox = () => {
//点击按钮如果是展开就折叠
if(selStatus.value) {
selClassName.value.pop()
selStatus.value = false
}else {
selClassName.value.push('expand')
selStatus.value = true
}
}
</script>
<style scoped lang="scss">
.container {
height: calc(100% - 50px);
background-color: antiquewhite;
display: flex;
justify-content: center;
//折叠样式
.sel-menu {
height: 50px;
width: 300px;
border: 1px solid #000;
overflow: hidden;
cursor: pointer;
transition: all 0.2s linear;
position: relative;
.btn {
width: 50px;
height: 30px;
position: absolute;
top: 0;
right: 0;
border: 1px solid red;
line-height: 30px;
text-align: center;
}
div {
width: 200px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
background-color: pink;
margin-bottom: 10px;
}
}
//展开样式
.expand {
height: 360px;
}
}
</style>