原生实现移动端轮播图 带触摸
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=640,user-scalable=no" /> <title>Document</title> <style> *{margin:0; padding:0;} #tabPic{ position:relative; width:100%; height:357px; overflow:hidden; } #picList{ width:500%; position:absolute; } #picList li{ float:left; width:20%; list-style:none; } #picList li img{ width:100%; height:357px; } .navList{ position:absolute; right:30px; bottom:30px; width:100px; height:15px; } .navList a{ width:10px; height:10px; border-radius:5px; background-color:white; float:left; margin-left:10px; } .active{ background-color:red !important; } </style> </head> <body> <section id="tabPic"> <ul id="picList"> <li> <img src="images/1.jpg"> </li> <li> <img src="images/2.jpg"> </li> <li> <img src="images/3.jpg"> </li> <li> <img src="images/4.jpg"> </li> <li> <img src="images/5.jpg"> </li> </ul> <nav class="navList"> <a class="active" href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> </nav> </section> <script> function fnTab(){ var tabPic = document.getElementById('tabPic'); var picList = document.getElementById('picList'); var aPicList = picList.getElementsByTagName('li'); var aNavList = document.getElementsByClassName('navList')[0].getElementsByTagName('a'); var iNow = 0; //记录页 var iX = 0;//记录的位置 var iW = 640; //页面的宽度 var timer = 0; //定时器 var iStartTouchX = 0; var iStartX = 0; picList.addEventListener('touchstart',fnStart,false); picList.addEventListener('touchmove',fnMove,false); picList.addEventListener('touchend',fnEnd,false); autoPlay(); function autoPlay(){ timer = setInterval(function(){ iNow++; iNow = iNow % aPicList.length; tab(); },1000); } function fnStart(ev){ ev = ev.changedTouches[0]; // console.log(ev); iStartTouchX = ev.pageX; //开始触摸点击的位置 iStartX = iX; //图片滚动的现在位置 clearInterval(timer); } function fnMove(ev){ ev = ev.changedTouches[0]; var iDis = ev.pageX - iStartTouchX; //移动的位置 - 开始触摸的位置 console.log(iDis); iX = iStartX + iDis; picList.style.WebkitTransform = picList.style.transform = "translateX("+iX+"px)"; } function fnEnd(){ iNow=iX/iW; iNow=-Math.round(iNow); if(iNow<0) { iNow=0; } if(iNow>aNavList.length-1) { iNow=aNavList.length-1; } tab(); autoPlay(); } function tab(){ iX= -iNow*iW; picList.style.WebkitTransition = picList.style.transition = '0.5s'; picList.style.WebkitTransform = picList.style.transform = "translateX("+iX+"px)" for(var i = 0 ; i < aNavList.length; i++){ aNavList[i].className = ""; } aNavList[iNow].className = "active"; } } fnTab(); </script> </body> </html>