<!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:400%; -webkit-transition:.3s; -webkit-transform:translate3d(0px,0px,0px); } .s-list>li{ height:25%; } .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 ; //开始 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; //当前的页数值与滑动距离数字累加,从而产生弹性效果 addNum += this.offsetY; //判断正数还是负数来进行弹性的方向 if ( this.offsetY > 0 ){ addNum = -num * winHeight + winHeight/4; }else{ addNum = -num * winHeight - winHeight/4; } oUl.style[‘-webkit-transform‘] = ‘translate3d(0px,‘+ addNum +‘px,0px)‘; } } //结束 var sliderEnd = function(){ //负数为往上,正数为往下 if ( this.offsetY > winHeight / 5 ) { // console.log(‘向上‘); if ( num > 0 ) { num--; }else{ nun = 0; } }else if ( this.offsetY < -winHeight / 5 ) { // console.log(‘向下‘); if ( num < aLi.length - 1 ) { num++; }else{ num = aLi.length -1; } } //真实的切换 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>
时间: 2024-10-14 00:37:51