js輪播圖封裝
阿新 • • 發佈:2018-11-10
banner.js結合move.js實現封裝輪播圖
banner.js程式碼
var swiper = (function() { var timer = null; return { init(ele) { if(typeof ele == 'string') { ele=document.querySelector(ele) } this.ele = ele; this.$tipBox = ele.querySelector('.banner-tip'); this.$tipLiAll = this.$tipBox.children; this.$perBtn = ele.querySelector('.left-btn'); this.$nextBtn = ele.querySelector('.right-btn'); this.$bannerBox = ele.querySelector('.banner-image'); this.$bannerLiAll = this.$bannerBox.children; var first = this.$bannerLiAll[0]; var last = this.$bannerBox.lastElementChild; this.$bannerBox.appendChild(first.cloneNode(true)); this.$bannerBox.insertBefore(last.cloneNode(true), first); this.$bannerBox.style.left = '-670px'; for(var i = 0; i < this.$tipLiAll.length; i++) { this.$tipLiAll[i].index = i; } this.index = 0; this.event(); this.autoPlay(); }, event(){ var that=this; this.$tipBox.onclick=function(e){ e=e||window.event; var target=e.target||e.srcElement; if (target.nodeName=='LI') { that.showImage(target.index); that.autoPlay(target.index); } }; this.$perBtn.onclick=function(){ that.showImage(--that.index); that.autoPlay(that.index); } this.$nextBtn.onclick=function(){ that.showImage(++that.index); that.autoPlay(that.index); } }, showImage(index){ var maxindex=this.$tipLiAll.length-1; if (index>maxindex) { index=0; this.$bannerBox.style.left=0; }else if (index<0) { index=maxindex; this.$bannerBox.style.left=-670*(maxindex+2)+'px'; } this.index=index; for (var i=0;i<this.$tipLiAll.length;i++) { this.$tipLiAll[i].removeAttribute('class') } this.$tipLiAll[index].className='active'; move(this.$bannerBox,'left',-670*(index+1)); }, autoPlay(index){ clearInterval(timer); var maxindex=this.$tipLiAll.length-1; index=index||0; timer=setInterval(()=>{ index++; if (index>maxindex) { index=0; } this.showImage(index) },2000) } } }())
move.js程式碼:
function move(ele, attr, target) { if (typeof ele == 'string') { ele = document.querySelector(ele); } clearInterval(ele.timer); var init = parseFloat(getStyle(ele, attr)); if (attr == 'opacity') { init *= 100; } ele.timer = setInterval(function () { console.log(1); var speed = (target - init) / 20; if(speed > 0) { speed = Math.ceil(speed); } else { speed = Math.floor(speed); } init += speed if ((speed >= 0 && init >= target) || (speed <= 0 && init <= target)) { init = target; clearInterval(ele.timer); } if (attr == 'opacity') { ele.style[attr] = init / 100; } else { ele.style[attr] = init + 'px'; } }, 10) } function getStyle(ele, attr) { if (window.getComputedStyle) { return window.getComputedStyle(ele, null)[attr]; } return ele.currentStyle[attr]; }