在公司手机端的vue编写中,需要用到一个轮播图,我一开始的时候使用的时候使用的是想在created中定义一个轮播函数,但是实际上这个轮播函数没有起作用,后面在网上看了一下,看到了网上的轮播图代码,是使用 transition-group来实现的,实践了一遍,现在代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ padding: 0; margin: 0; } .carousel-wrap{ width: 600px; position: relative; margin: 0 auto; } .carousel { position: relative; height: 500px; width: 600px; background-color: #fff; overflow: hidden; } .slide-ul { width: 100%; height: 100%; } li { position: absolute; width: 100%; height: 100%; } img { width: 100%; height: 100%; } .list-enter-active { transition: all 1s ease; transform: translateX(0) } .list-leave-active { transition: all 1s ease; transform: translateX(-100%) } .list-enter { transform: translateX(100%) } .list-leave { transform: translateX(0) } .carousel-items{ position: absolute; bottom: 10px; margin:0 auto; width: 100%; text-align: center; } .circle{ display: inline-block; width: 10px; height: 10px; border-radius: 100%; border: 1px solid black; margin: 0 10px; } .item-active{ background-color: whitesmoke; } </style> </head> <body> <div id="carousel" class="carousel-wrap"> <div class="carousel"> <transition-group tag="ul" class="slide-ul" name="list"> <li v-for="(list,index) in slideList" :key="index" v-show="index===currentIndex" @mouseenter="stop" @mouseleave="go"> <a href="list.clickHref"> <img :src="list.img" :alt="list.desc"> </a> </li> </transition-group> </div> <div class="carousel-items"> <span v-for="(item,index) in slideList.length" class="circle" :class="{‘item-active‘:index===currentIndex}" @click="change(index)"></span> </div> </div> <script src="vue.js"></script> <script type="application/ecmascript"> new Vue({ el: "#carousel", data:{ slideList: [ { clickHref:"1", img:"images/book5.jpg" }, { clickHref:"2", img:"images/book6.jpg" }, { clickHref:"3", img:"images/book7.jpg" } ], currentIndex:0, timer:‘‘ }, methods:{ autoPlay:function(){ this.currentIndex++; if (this.currentIndex > this.slideList.length - 1) { this.currentIndex = 0 } }, stop: function () { clearInterval(this.timer); this.timer=null; }, go: function(){ this.timer=setInterval(()=>{ this.autoPlay() },4000) }, change: function(index){ this.currentIndex=index; } }, created(){ this.$nextTick(()=>{ this.timer=setInterval(()=>{ this.autoPlay() },4000) } ) } }) </script> </body> </html>
如上:
时间: 2024-10-14 12:10:51