var banner=document.querySelector(".jd_banner"); var imgBox=banner.querySelector("ul:first-of-type"); var first=imgBox.querySelector("li:first-of-type"); var last=imgBox.querySelector("li:last-of-type"); imgBox.appendChild(first.cloneNode(true)); imgBox.insertBefore(last.cloneNode(true),imgBox.firstChild); var lis=imgBox.querySelectorAll("li"); var count=lis.length; //count的值需要在 添加克隆元素后获取 var bannerWidth=banner.offsetWidth; imgBox.style.width=count*bannerWidth+"px"; var index=1; //声明一个变量index 记录索引 所因为实际的第二张 观众的第一张 for(var i=0;i<lis.length;i++){ lis[i].style.width=bannerWidth+"px"; } imgBox.style.left = -index*bannerWidth+'px'; var startX,moveX,distanceX; var isEnd = true; imgBox.addEventListener('touchstart', function (e) { startX=e.targetTouches[0].clientX; }); imgBox.addEventListener('touchmove', function (e) { if (isEnd) { moveX=e.targetTouches[0].clientX; distanceX=moveX-startX; imgBox.style.left = (-index*bannerWidth+distanceX)+'px'; //在move中 别搞错了 是手指动的距离加上一整张图片的距离 } }); imgBox.addEventListener('touchend', function (e) { //真的牛P touchend 记住啊! isEnd=false; if(Math.abs(distanceX) > 100) { console.log(distanceX) if (distanceX > 0) { //结束位置 - 初始位置 index--; //往前走 } else { index++; //往后走 } imgBox.style.transition = 'all 0.5s'; imgBox.style.left = -index*bannerWidth+'px'; } else if(Math.abs(distanceX)>0) { imgBox.style.transition = 'all 0.5s'; imgBox.style.left = -index*bannerWidth+'px'; } startX =0; moveX =0; // move时已经给distance 赋值了如果再拖 end时 distance的值是唯一的 所以要重新赋值 distanceX=0; }); imgBox.addEventListener('webkitTransitionEnd', function () { if(index==0) { //== 0 不是 = 0 index=count-2; //一定别忘了 索引也要改变 下面要让他瞬间跑到固定的位置 imgBox.style.transition = 'none'; //第一张和最后一张的运行 不需要过渡 而是直接跳转 imgBox.style.left = -index*bannerWidth+'px'; } else if(index==count-1){ index=1; imgBox.style.transition = 'none'; imgBox.style.left = -index*bannerWidth+'px'; } setTimeout(function () { isEnd=true; },100) }); // isEnd 重要 知识点 , 最初当isEnd为 true时,move 开始进行 , 当touchend是 isend赋值为false,不让用户在过渡效果结束前进行下一次move //在过渡结束后 也就是 webkitTransitionEnd 重新开启isend true, //这是关系到代码的执行时间 上一次过渡还没执行完 ,用户再进行一次拖拽 会导致 webkitTransitionEnd里的代码没来得及执行! //js 的代码执行时间在很多时候都是必须注意的问题
手机轮播初体验
最新推荐文章于 2021-06-17 04:35:23 发布