vue中實現簡單輪播效果
阿新 • • 發佈:2019-01-08
html:
<div class="cate-main"> <div class="carousel-contain"> <--圖片部分--> <ul class="carousel-wrap transition"> <li class="carousel-slide"> <img src="../assets/images/category/banner1.png" alt="圖1"> </li> <li class="carousel-slide"> <img src="../assets/images/category/banner2.png" alt="圖2"> </li> <li class="carousel-slide"> <img src="../assets/images/category/banner3.png" alt="圖3"> </li> <li class="carousel-slide"> <img src="../assets/images/category/banner1.png" alt="圖1"> </li> </ul> <--切換按鈕部分--> <p class="carousel-button-wrap"> <span class="carousel-button-slide" :class="{active: activeIndex == 0 || activeIndex == 3}" @click="switchPic (0)"></span> <span class="carousel-button-slide" :class="{active: activeIndex == 1}" @click="switchPic (1)"></span> <span class="carousel-button-slide" :class="{active: activeIndex == 2}" @click="switchPic (2)"></span> </p> </div> </div>
js:
data () {
return {
timeId: 0,
timeOutId: 0,
activeIndex: 0
}
},
activated () {
this.carousel ();
},
methods: { carousel () { clearTimeout(this.timeOutId); let ul = document.getElementsByClassName('carousel-wrap')[0]; let li = document.getElementsByClassName('carousel-wrap')[0].getElementsByTagName("li"); let span = document.getElementsByClassName('carousel-button-wrap')[0].getElementsByTagName("span"); let num = 0; let len = li.length; let self = this; this.timeId = setInterval(function(){ num = ++num == len ? 0 : num; self.activeIndex = num; if ( num == 0 ) { ul.classList.remove('transition'); ul.style.transform = 'translateX' + '(' + '-' + 78.57*num + 'rem' + ')'; } else { ul.classList.add('transition'); ul.style.transform = 'translateX' + '(' + '-' + 78.57*num + 'rem' + ')'; } }, 2500); }, switchPic (index) { clearInterval(this.timeId); this.activeIndex = index; let ul = document.getElementsByClassName('carousel-wrap')[0]; if ( index == 0 ) { ul.style.transform = 'translateX' + '(' + '-' + 78.57*index + 'rem' + ')'; } else { ul.style.transform = 'translateX' + '(' + '-' + 78.57*index + 'rem' + ')'; } let self = this; this.timeOutId = setTimeout(function () { self.carousel (); }, 3000) } }
destoryed () {
clearInterval(this.timeId);
}
css:
.cate-main { width: 78.57rem; height: 57.14rem; position: relative; .carousel-contain{ width: 78.57rem; height: 57.14rem; overflow: hidden; .carousel-wrap{ list-style: none; width: 314.29rem; padding: 0; .carousel-slide{ float: left; } } .transition { transition: all 1s ease; } .carousel-button-wrap { position: absolute; bottom: 0; left: 28.285rem; .carousel-button-slide { display: inline-block; width: 6rem; height: 0.5rem; margin-right: 2rem; opacity: 0.5; background: #FFFFFF; border-radius: 0; } .active{ opacity: 1; } } } }