这里主要要完成的效果是:当前元素左移消失(过程中透明度逐渐为0),新元素紧随其后左移到上一个元素的位置(透明度在移动的过程中从0到1)。这里出现的问题是两个div并未紧贴着完成动画,而是一直保持这距离,使得整个效果过于生硬。
以下是全部源代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<style>
.d {
position: relative;
border: 1px solid red;
width: 30px;
height: 30px;
}
@keyframes show {
0% {
opacity: 0;
transform: translateX(30px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
@keyframes hide {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(-30px);
}
}
.show-enter-active {
animation: show 2s;
}
.show-leave-active {
animation: hide 1s;
}
.show-enter, .show-leave-to {
opacity: 0;
}
.wrap {
display: flex;
}
</style>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
<div class="wrap">
<transition name="show">
<div class="d" v-for="item in list" :key="item.id" v-if="count === item.id">
{{ item.text }}
</div>
</transition>
</div>
<button @click="add">add</button>
</div>
<script>
new Vue({
el: '#app',
data () {
return {
message: 'Hello Vue.js!',
count: 0,
list: [
{id: 0, text: 'aaa'},
{id: 1, text: 'bbb'},
{id: 2, text: 'ccc'}
]
}
},
methods: {
add: function () {
if (this.count < this.list.length - 1) {
this.count += 1;
} else {
this.count = 0;
}
}
}
})
</script>
</body>
</html>
没有平滑的过渡是因为
div.b
的横向排列方式。当前一个
div
消失时,会突然增加后者需要前进的距离,这样就不协调了。也是之前设置成2s
的原因。