標籤:startx idt event 觸摸位置 移動端 func == console alert
1 <div id="box" style="width:100%;height:100%;border:1px solid red;"></div> 2 3 <script> 4 //定義變數,用於記錄座標和角度 5 var startx,movex,endx,nx; 6 //開始觸摸函數,event為觸摸對象 7 function touchs(event){ 8 event.preventDefault();//阻止瀏覽器預設滾動事件 9 var box = document.getElementById(‘box‘);//擷取DOM標籤10 if(event.type=="touchstart"){//通過if語句判斷event.type執行了哪個觸摸事件11 console.log(‘開始‘);12 var touch = event.touches[0];//擷取開始的位置數組的第一個觸摸位置13 startx = Math.floor(touch.pageX);//擷取第一個座標的X軸14 }else if(event.type=="touchmove"){//觸摸中的座標擷取15 console.log(‘滑動中‘);16 var touch = event.touches[0];17 movex = Math.floor(touch.pageX);18 }else if(event.type == "touchend" || event.type == "touchcancel"){//當手指離開螢幕或系統取消觸摸事件的時候19 endx = Math.floor(event.changedTouches[0].pageX);//擷取最後的座標位置20 console.log(‘結束‘);21 nx = endx-startx;//擷取開始位置和離開位置的距離22 //判斷滑動方向23 if(nx > 0){24 alert(‘右滑動‘);25 return false;26 }else{27 alert(‘左滑動‘);28 return false;29 }30 }31 }32 //添加觸摸事件的監聽,並直行自訂觸摸函數33 box.addEventListener(‘touchstart‘,touchs,false);34 box.addEventListener(‘touchmove‘,touchs,false);35 box.addEventListener(‘touchend‘,touchs,false);36 </script>
js移動端左右滑動事件