<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,target-densitydpi=high-dpi,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="apple-mobile-web-app-capable" content="yes" /> <title>slider</title> <style> *{ padding:0; margin:0; } html , body , #slider { height:100%; overflow: hidden; } .s-list{ height:1000%; -webkit-transition:.3s; -webkit-transform:translate3d(0px,0px,0px); } .s-list>li{ height:10%; } .s-list>li:nth-child(1){background:#00be9c;} .s-list>li:nth-child(2){background:#50d78a;} .s-list>li:nth-child(3){background:#2c97df;} .s-list>li:nth-child(4){background:#9c56b8;} </style> </head> <body> <section id="slider"> <ul class="s-list"> <li>第一屏</li> <li>第二屏</li> <li>第三屏</li> <li>第四屏</li> </ul> </section> <script> function slider( id ){ //获取所要的 DOM 元素 var oSlider = document.getElementById('slider'); var oUl = oSlider.getElementsByTagName('ul')[0]; var aLi = oUl.getElementsByTagName('li'); var winHeight = document.body.clientHeight; var startY , offsetY , num = 0 , addNum = 0 ; //获取百分比高度 oUl.style.height = 100 * aLi.length +'%'; for( var i = 0 , len = aLi.length ; i < len ; i++ ){ aLi[i].style.height = 100 / aLi.length +'%'; } //开始 var sliderStart = function( event ){ this.startY = event.touches[0].pageY; } //移动 var sliderMove = function( event ){ //单手操作才执行 if ( event.targetTouches.length == 1 ) { event.preventDefault(); //获取移动的距离 this.offsetY = event.targetTouches[0].pageY - this.startY ; var addNum = this.offsetY + parseInt(window.getComputedStyle( oUl , null)['-webkit-transform'].replace(/[a-z()]/g , '').split(',')[5]); //防止跨屏 if ( this.offsetY > 0 ) { if ( addNum > -winHeight * (num - 1) ) { addNum = -winHeight * (num - 1); } }else{ if ( addNum < -winHeight * (num + 1) ) { addNum = -winHeight * (num + 1); } } oUl.style['-webkit-transform'] = 'translate3d(0px,'+ addNum +'px,0px)'; } } //结束 var sliderEnd = function(){ //负数为往上,正数为往下 if ( this.offsetY > 0 ) { // console.log('向上'); if ( num > 0 ) { num--; }else{ num = 0; } }else if ( this.offsetY < 0 ) { // console.log('向下'); if ( num < aLi.length - 1 ) { num++; }else{ num = aLi.length -1; } }
//清空防止点击切换
this.offsetY = 0;
//真实的切换 oUl.style['-webkit-transform'] = 'translate3d(0px,'+ -num*winHeight +'px,0px)'; //让累加数值为当前页面切换到的数值 addNum = -num*winHeight; } //让最顶层的 DIV 处理事件,然而 ul 根据,最顶层的 DIV 操作来移动 oSlider.addEventListener('touchstart' , sliderStart); oSlider.addEventListener('touchmove' , sliderMove); oSlider.addEventListener('touchend' , sliderEnd); } slider('slider'); </script> </body> </html>