實現移動端輪播圖
阿新 • • 發佈:2018-12-28
1、移動端實現滑動切換輪播圖,主要由touch(touchstart,touchmove,touchend)事件實現。在touch事件中可以通過 e.touches[0].clientX獲取當前觸控點的位置,在touchend事件中沒有e.touches[0].clientX值
var banner=function(){ /* *1、無縫滾動和無縫滑動 *2、點盒子對應改變 *3、可以滑動 *4、當滑動距離不夠時 吸附回去 *5、當滑動距離夠了時 跳轉上/下一張 */ var banner=document.querySelector('.jd_bannar'); var imgBox=banner.querySelector('ul:first-child'); var pointBox=banner.querySelector('ul:last-child'); var points=pointBox.querySelectorAll('li'); var width=banner.offsetWidth; var addTransition=function(){ imgBox.style.transition = 'all 0.2s'; imgBox.style.webkitTransition='all 0.2s'; } var removeTransition=function(){ imgBox.style.transition = 'none'; imgBox.style.webkitTransition='none'; } var setTranslateX=function(tx){ imgBox.style.transform = 'translateX('+tx+'px)'; imgBox.style.webkitTransform = 'translateX('+tx+'px)'; } var index=1; var timer=setInterval(function(){ index++; addTransition(); setTranslateX((-index*width)) },1000) //監聽 transition結束之後的事件 imgBox.addEventListener('transitionend',function(){ if(index==9){ index=1; removeTransition(); setTranslateX((-index*width)) }else if(index<=0){ index=8; removeTransition(); setTranslateX((-index*width)) } setPoint() }) var setPoint=function(){ for(var i=0;i<points.length;i++){ points[i].classList.remove('now') } points[index-1].classList.add('now') } var stratX=0; var disX=0; var ismove=false; imgBox.addEventListener('touchstart',function(e){ clearInterval(timer) stratX=e.touches[0].clientX; }) imgBox.addEventListener('touchmove',function(e){ var moveX=e.touches[0].clientX; disX=moveX-stratX; /*計算定位*/ var tx=-index*width+disX; //清除定位 removeTransition(); setTranslateX(tx); ismove=true; }) imgBox.addEventListener('touchend', function(e){ /*disX確定滑動距離,判斷是否吸附或者跳轉*/ if(ismove && Math.abs(disX)<(width/3)){ addTransition(); setTranslateX(-index*width) }else{ //判斷滑動方向 if(disX>0){ index--; }else{ index++ } addTransition(); setTranslateX(-index*width) } clearInterval(timer) timer=setInterval(function(){ index++; addTransition(); setTranslateX((-index*width)) },1000) //初始化資料 stratX=0; ismove=false; disX=0; }) }