【发布时间】:2020-12-19 08:50:01
【问题描述】:
我正在尝试从列表中添加和删除项目。我可以为列表设置动画,但容器的高度没有动画。
正如您在预览中看到的那样,红色容器在没有过渡的情况下获得和失去高度。
如何在添加或删除项目时为容器的高度设置动画?
问候
【问题讨论】:
标签: css vue.js vuejs2 transition
我正在尝试从列表中添加和删除项目。我可以为列表设置动画,但容器的高度没有动画。
正如您在预览中看到的那样,红色容器在没有过渡的情况下获得和失去高度。
如何在添加或删除项目时为容器的高度设置动画?
问候
【问题讨论】:
标签: css vue.js vuejs2 transition
只需将 CSS 属性添加到您的容器:transition: .3s 其中 3s 是转换时间的值并动态更改容器的高度。
【讨论】:
v-bind 我认为的样式属性
this.$refs.thatElement.offsetHeight 计算元素的高度并将其添加到高度。
<template>
<div :style="{'max-height': list.length * 24 + 'px'}" class="hgh bg-red-400 container mx-auto">
<transition-group name="fade-top" tag="ul">
<li v-for="(item, index) in list" :key="index">
<p>{{ item }}</p>
</li>
</transition-group>
<button class="mt-4 px-5 py-2 bg-indigo-400 text-white" @click="add">Add</button>
<button class="mt-4 ml-4 px-5 py-2 bg-indigo-400 text-white" @click="remove">Remove</button>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
list: [1, 2, 3, 4]
};
},
methods: {
add() {
this.list.push(Math.round(Math.random() * 10));
},
remove() {
this.list.pop();
}
}
};
</script>
<style>
.fade-top-enter-active,
.fade-top-leave-active {
transition: opacity 0.3s, transform 0.35s;
}
.fade-top-enter {
opacity: 0;
transform: translateY(8%);
}
.hgh {
height: 100vh;
transition: max-height 300ms;
}
.fade-top-leave-to {
opacity: 0;
transform: translateY(-8%);
}
</style>
高度转换通常使用max-height 完成。首先,您设置一个大高度,例如 100vh,然后在您的 div 中根据您的列表长度计算 max-height
:style="{'max-height': list.length * 24 + 'px'}"
如果你问24 来自哪里,它是你的p 元素的高度
在你的 div 中添加一个 css 类
.hgh {
height: 100vh;
transition: max-height 300ms;
}
【讨论】:
p 标签在实际应用中不能有固定的高度。另外,没有像height 100vh这样的补丁可以吗?