效果图
利用vue提供的transtion标签实现动画
css代码;
<style>
#app{
width: 400px;
height: 300px;
margin: 50px auto;
position: relative;
text-align: center;
overflow: hidden;
}
img{
width: 100%;
height: 100%;
position: absolute;
top: 30px;
left: 0;
}
/* 下一张的动画效果 */
.next-enter{
left: 400px;
}
.next-enter-active{
transition: all 1s;
}
.next-enter-to{
left: 0px;
}
.next-leave{
left: 0px;
}
.next-leave-active{
transition: all 1s;
}
.next-leave-to{
left: -400px;
}
/* 上一张动画效果 */
.pre-enter{
left: -400px;
}
.pre-enter-active{
transition: all 1s;
}
.pre-enter-to{
left: 0px;
}
.pre-leave{
left: 0;
}
.pre-leave-active{
transition: all 1s;
}
.pre-leave-to{
left: 400px;
}
</style>
html代码:
这里小编钻了漏子,利用小编的图片共有5张,并且命名时1,2,3,4,5,所以利用v-for遍历了数字,然后拼接图片路径,如果看不懂可以联系我。
<div id="app">
<button @click="page(-1)">上一页</button>
<button @click="page(1)">下一页</button>
<transition :name="aniName">
<img :src=`../image/${n}.webp` alt="" v-for="n in 5" :key="n" v-if="n==current" @mouseover="f1" @mouseout="f2">
</transition>
</div>
js代码:
<script>
var app = new Vue({
el:"#app",
data:{
current:1,//播放第几张图片
aniName:"",//过渡动画的名字
isChange:true,
timer:null
},
created() {
this.timer = setInterval(() => {
this.page(1)
}, 2000);
},
methods: {
f1(){
clearInterval(this.timer)
},
f2(){
this.timer = setInterval(() => {
this.page(1)
}, 2000);
},
page(offset){
// 这里的isChange是为了防抖,避免连续多次点击
if (this.isChange==false) {
return
}else{
this.isChange = false
}
this.current = this.current+offset
// 这里虽然只有5张图片,但是如果遍历到5的时候就返回第一张,那么第五张图片的动画没走完就返回第一张了,所以要遍历到6,这样可以实现无缝轮播。
if (this.current>=6) {
this.current = 1
}
if (this.current<=0) {
this.current = 5
}
if (offset==1) {
this.aniName = "next"
}else{
this.aniName = "pre"
}
setTimeout(()=>{
this.isChange = true
},500)
}
},
})
</script>