本文實(shí)例講述了JS手機(jī)端touch事件計(jì)算滑動(dòng)距離的方法。分享給大家供大家參考,具體如下:
計(jì)算手勢(shì)在手機(jī)屏幕上滑動(dòng)時(shí),手勢(shì)滑動(dòng)的距離,代碼如下:
function wetherScroll(){ var startX = startY = endX =endY =0; var body=document.getElementsByTagName("body"); body.bind('touchstart',function(event){ var touch = event.targetTouches[0]; //滑動(dòng)起點(diǎn)的坐標(biāo) startX = touch.pageX; startY = touch.pageY; // console.log("startX:"+startX+","+"startY:"+startY); }); body.bind("touchmove",function(event){ var touch = event.targetTouches[0]; //手勢(shì)滑動(dòng)時(shí),手勢(shì)坐標(biāo)不斷變化,取最后一點(diǎn)的坐標(biāo)為最終的終點(diǎn)坐標(biāo) endX = touch.pageX; endY = touch.pageY; // console.log("endX:"+endX+","+"endY:"+endY); }) body.bind("touchend",function(event){ var distanceX=endX-startX, distanceY=endY - startY; // console.log("distanceX:"+distanceX+","+"distanceY:"+distanceY); //移動(dòng)端設(shè)備的屏幕寬度 var clientHeight; =document.documentElement.clientHeight; // console.log(clientHeight;*0.2); //判斷是否滑動(dòng)了,而不是屏幕上單擊了 if(startY!=Math.abs(distanceY)){ //在滑動(dòng)的距離超過(guò)屏幕高度的20%時(shí),做某種操作 if(Math.abs(distanceY)>clientHeight*0.2){ //向下滑實(shí)行函數(shù)someAction1,向上滑實(shí)行函數(shù)someAction2 distanceY <0 ? someAction1():someAction2(); } } startX = startY = endX =endY =0; })}希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答