一、功能实现描述
n个div模块实现左右滑动,支持移动端触摸
二、实现原理以及思路
1.容器宽度为n*100%,隐藏溢出内容
2.监听触摸事件,判断移动方向
2.根据div的个数,计算生成一个数组,保存每个div的index,和计算出容器TranslateX()的值
3.根据计算的值,在滑动事件中给容器添加style样式,来实现某个div在可见视图中
三、代码
1.js
function Slide() { var direction=0,start=0,end=0;//负左划 var currentIndex=0,model=[]; var boxes = document.querySelectorAll('div.slideItem'); var wrap = document.querySelector('div.slideWrap'); var prev = document.querySelector('div.prev'); var next = document.querySelector('div.next'); var count=boxes.length; var max=count,min=-1; var moveright=function () { var prev=getPos(currentIndex-1,1); if(currentIndex>=0){ wrap.style.cssText+='transform:translateX(-'+prev+'%)'; currentIndex--; } currentIndex=correctCurrentIndex(currentIndex); console.log(currentIndex) }; var moveleft=function () { var next=getPos(currentIndex+1,0); if(currentIndex<=3){ wrap.style.cssText+='transform:translateX(-'+next+'%)'; currentIndex++; } currentIndex=correctCurrentIndex(currentIndex); console.log(currentIndex) }; var getPos=function(pos,isRight){ var _index; if(isRight){ _index=pos<0?0:pos; } else{ _index=pos>count-1?count-1:pos; } return model[_index].pos; }; var movestart = function (e) { start=e.changedTouches[0].screenX; }; var moveend = function (e) { end=e.changedTouches[0].screenX; direction=end-start; console.log(direction) direction>0?moveright():moveleft(); }; //纠正下标边界 var correctCurrentIndex=function (_currentIndex) { _currentIndex=_currentIndex<=min?0:_currentIndex; _currentIndex=_currentIndex>=max?max-1:_currentIndex; return _currentIndex; }; wrap.style.cssText+=('width:'+count*100+'%'); for(var i=0;i<boxes.length;i++){ boxes[i].style.cssText+=('width:'+100/count+'%'); boxes[i].addEventListener('touchstart', movestart); boxes[i].addEventListener('touchend', moveend); model.push({order:i,pos:(i*(100/count))}) } this.setCurrentIndex=function (newCurrent) { direction=+(newCurrent>currentIndex); currentIndex=newCurrent; }; this.getCurrentIndex=function () { return currentIndex; }; prev.addEventListener('click',moveright.bind(this)); next.addEventListener('click',moveleft.bind(this)); }
2.html
<div class="container"> <div class="prev"><</div> <div class="next">></div> <div class="slideWrap"> <div class="slideItem"><i>1</i></div> <div class="slideItem"><i>2</i></div> <div class="slideItem"><i>3</i></div> </div> </div>