Recently has been doing mobile phone app H5 Development, in the development process, often encounter a lot of sliding events, write a demo, share some of their own wording. (such as bad writing, light spray!)
Direct Sticker Code
HTML CSS Code
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "UTF-8"><title>Touch Demo</title><styletype= "Text/css">#demo{Margin-top:200px;Height:200px;Display:-webkit-box;}#demo1{background:Red;width:100%;Height:200px;}#demo2{background:Blue;width:100%;Height:200px;}Body{Overflow:Hidden;}</style></Head><Body> <DivID= "Demo"> <DivID= "Demo1"></Div> <DivID= "Demo2"></Div> </Div></Body></HTML>
JS Code
var slidedom = document.getElementById ("demo");//sliding area var length = slidedom.children.length;//Sub-class node length var index = 0;// Initial subscript Window.prevx = 0;slidedom.addeventlistener (' Touchstart ', Touchstart, false); Slidedom.addeventlistener (' Touchmove ', Touchmove, false); Slidedom.addeventlistener (' Touchend ', touchend, false);//Start sliding function Touchstart (e) { var point = GetPoint (e); window.startx = Point.pagex;console.log (WINDOW.STARTX);};/ /sliding Process function Touchmove (e) {e.preventdefault ();//block default behavior var point = GetPoint (e); window.movex = Point.pagex; Window.deltax = Window.movex-window.startx;domove (WINDOW.DELTAX+WINDOW.PREVX);};/ /End Sliding function touchend (e) {var x = Math.Abs (window.deltax); var item_w = document.getElementById ("Demo1"). offsetwidth; if (window.deltax>0) {if (x>item_w) {var indexd = Math.Round (x/item_w); index = Index-indexd;} Else{if (X/item_w > 0.3) {index--}}}else if (window.deltax<0) {if (x>item_w) {var indexd = Math.Round (X/item_w); index = index + indexd;} Else{if (X/item_w > 0.3) {index++;}}}if (Index >= (length-1)) {index = length-1;} if (index <0) {index = 0;} Window.prevx =-index*item_w;domove (window.prevx,true);};/ /default function GetPoint (e) {return e.touches) with the position of the first finger. E.touches[0]: e;};/ /Use Transform Move function domove (x,t) {if (t) {Slidedom.setattribute (' style ', ' transform:translate ' (' + x + ' px, 0px); Transition:transform 300ms Ease ');} Else{slidedom.setattribute (' style ', ' transform:translate ' (' + x + ' px, 0px); Transition:transform 0ms Ease ');}};
If the user is a multi-fingered operation, the default is calculated with the position of the first finger.
At the end of the event, the position of the Div movement is calculated.
In the range of index, if the div moves beyond 0.3, switch to the next index div;
Mobile-H5 development (sliding events)