vue实现元素的伸缩
Vue 实现元素伸缩的方法
使用 CSS transition 和 v-bind:class
通过 Vue 的 v-bind:class 动态切换 CSS 类,结合 CSS 的 transition 属性实现平滑的伸缩效果。
<template>
<div
class="expandable-element"
:class="{ 'expanded': isExpanded }"
@click="isExpanded = !isExpanded"
>
点击伸缩
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false
};
}
};
</script>
<style>
.expandable-element {
width: 100px;
height: 50px;
background: #42b983;
transition: all 0.3s ease;
overflow: hidden;
}
.expanded {
height: 200px;
}
</style>
使用动态样式绑定
通过 Vue 的 v-bind:style 直接绑定动态样式,实现更灵活的伸缩控制。
<template>
<div
class="expandable-element"
:style="{ height: currentHeight + 'px' }"
@click="toggleHeight"
>
点击伸缩
</div>
</template>
<script>
export default {
data() {
return {
currentHeight: 50,
isExpanded: false
};
},
methods: {
toggleHeight() {
this.currentHeight = this.isExpanded ? 50 : 200;
this.isExpanded = !this.isExpanded;
}
}
};
</script>
<style>
.expandable-element {
width: 100px;
background: #42b983;
transition: height 0.3s ease;
overflow: hidden;
}
</style>
使用第三方动画库
结合 vue-transition 或 animate.css 实现更复杂的伸缩动画效果。
<template>
<transition name="expand">
<div v-if="show" class="expandable-element">
动画伸缩效果
</div>
</transition>
<button @click="show = !show">切换</button>
</template>
<script>
export default {
data() {
return {
show: false
};
}
};
</script>
<style>
.expandable-element {
width: 100px;
height: 50px;
background: #42b983;
}
.expand-enter-active, .expand-leave-active {
transition: all 0.5s ease;
overflow: hidden;
}
.expand-enter, .expand-leave-to {
height: 0;
opacity: 0;
}
</style>
注意事项
- 确保为伸缩元素设置
overflow: hidden,避免内容溢出时影响动画效果。 - 使用
transition时需明确指定变化的属性(如height或all)。 - 动态绑定的高度值需带单位(如
px或%)。







