动画
<style>
@keyframes leftToRight {
50% {
transform: translate3d(200px,200px,0)
}
}
.animation{
animation: leftToRight 2s;
}
</style>
过渡
<style>
.transition{
transition:background-color 3s ease
}
.blue{
background-color: blue;
}
.green{
background-color: green;
}
</style>
<div id="root">
<div :class="animate">hello</div>
<button @click="change">切换</button>
</div>
const app = new Vue({
el: "#root",
data() {
return {
animate:{
transition: true,
blue:true,
green:false
}
}
},
methods: {
change(){
this.animate.blue = !this.animate.blue;
this.animate.green = !this.animate.green;
}
}
})
动画案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/[email protected]"></script>
<style>
@keyframes shakeEnter {
0%{
transform:translateX(-100px)
}
}
@keyframes shakeLeave {
100%{
transform:translateX(100px)
}
}
.v-enter-active{
animation: shakeEnter 2s ease-out;
transition: opacity 2s ease-out;
}
.v-leave-active{
animation: shakeLeave 2s ease-out;
transition: opacity 2s ease-out;
}
.v-enter-from,.v-leave-to{
opacity: 0;
}
body {
margin: 200px;
}
</style>
</head>
<body>
<div id="root">
<transition>
<div v-show="show">hello</div>
</transition>
<button @click="change">切换</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
show: false
}
},
methods: {
change() {
this.show = !this.show;
}
}
})
const vm = app.mount("#root");
</script>
</body>
</html>
v-enter-from 和v-leave-from 都是触发过渡的一瞬间生效,然后下一帧就失效,过渡期间会给dom添加enter-active、enter-to或者leave-active、leave-to这个时候transition:all 1s ease-in; 就会起作用
不用css做动画,而用js
案例:
<body>
<div id="root">
<transition :css="false"
@before-enter="handleBeforeEnter"
@enter="handleEnter"
@after-enter="handleEnterEnd"
>
<div v-show="show">hello</div>
</transition>
<button @click="change">切换</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
show: false
}
},
methods: {
change() {
this.show = !this.show;
},
handleBeforeEnter(el){
el.style.color = 'red'
},
handleEnter(el,done){
const timer = setInterval(()=>{
const color = el.style.color;
el.style.color = color === 'red' ? 'green' : 'red';
},1000)
setTimeout(()=>{
clearInterval(timer);
done(); //动画结束
},3000)
},
handleEnterEnd(){
alert("动画结束")
}
}
})
const vm = app.mount("#root");
</script>
</body>
</html>
当有两个dom同时做动画,要求先出去再进来时,可以写mode
< transition mode=“out-in” appear> //appear是初次展示也要动画