js案例 移動端左右滑動touch+transform
阿新 • • 發佈:2019-01-28
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no"> <style> *{ padding: 0; margin: 0; /*margin-top:100px;*/ } #move{ height: 80px; width: 99%; border: 1px solid red; font-size: 19px; text-align: center; padding-top: 20px; box-sizing: border-box; font-weight: 700; } .box{ height: 64px; width: 200px; border: 4px solid red; margin: 80px auto; /*overflow: hidden;*/ } .box2{ height: 64px; width: 260px; border: 4px solid black; /*padding: 2px;*/ box-sizing:border-box; } .left{ height: 56px; width: 200px; border: 4px solid royalblue; float: left; box-sizing:border-box; } .right{ height: 56px; width: 52px; border: 4px solid chartreuse; float: right; box-sizing:border-box; /*transform: translate(100px);*/ } button{ height: 50px; width: 100%; font-size: 19px; } </style> </head> <body> <div id="move"> 移動端觸屏左右滑動 </div> <div class="box"> <div class="box2"> <div class="left"></div> <div class="right"></div> </div> </div> <button >移動端點選滑動</button> </body> <script type="text/javascript"> window.onload = function(){ var stus = true; var but = document.querySelector('button'); var box2 = document.querySelector('.box2'); but.onclick = function(){ console.log(stus); var right = document.querySelector('.box2'); if(stus){ right.style.transform = "translate("+-52+"px)"; right.style.transition = 'all .5s'; stus=!stus; }else{ right.style.transform = ""; stus=!stus; } } //開始移動時 要做的事 box2.addEventListener('touchstart',function(event){ startX = event.touches[0].clientX; console.log(startX); }) //移動過程中 要做的事 box2.addEventListener('touchmove',function(event){ moveX = event.touches[0].clientX - startX; console.log(moveX); }) //移動結束時 要做的事 box2.addEventListener('touchend',function(event){ var right = document.querySelector('.box2'); if(stus){ right.style.transform = "translate("+-52+"px)"; right.style.transition = 'all .7s'; stus=!stus; }else{ right.style.transform = ""; stus=!stus; } }) } </script> </html>