判斷手指滑動的方向
方法1 (通過橫向和縱向距離比較)
var startX ,startY; $("body").on("touchstart", function(e) { e.preventDefault(); startX = e.originalEvent.changedTouches[0].pageX, startY = e.originalEvent.changedTouches[0].pageY; }); $("body").on("touchmove", function(e) { e.preventDefault(); var moveEndX = e.originalEvent.changedTouches[0].pageX, moveEndY = e.originalEvent.changedTouches[0].pageY, X = moveEndX - startX, Y = moveEndY - startY; if ( Math.abs(X) > Math.abs(Y) && X > 0 ) { alert("left 2 right"); } else if ( Math.abs(X) > Math.abs(Y) && X < 0 ) { alert("right 2 left"); } else if ( Math.abs(Y) > Math.abs(X) && Y > 0) { alert("top 2 bottom"); } else if ( Math.abs(Y) > Math.abs(X) && Y < 0 ) { alert("bottom 2 top"); } else{ alert("just touch"); } });
方法2 (通過滑動兩點的角度判斷)
var startx, starty; //獲得角度 function getAngle(angx, angy) { return Math.atan2(angy, angx) * 180 / Math.PI; }; //根據起點終點返回方向 1向上 2向下 3向左 4向右 0未滑動 function getDirection(startx, starty, endx, endy) { var angx = endx - startx; var angy = endy - starty; var result = 0; //如果滑動距離太短 if (Math.abs(angx) < 2 && Math.abs(angy) < 2) { return result; } var angle = getAngle(angx, angy); if (angle >= -135 && angle <= -45) { result = 1; } else if (angle > 45 && angle < 135) { result = 2; } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) { result = 3; } else if (angle >= -45 && angle <= 45) { result = 4; } return result; } //手指接觸螢幕 document.addEventListener("touchstart", function(e) { startx = e.touches[0].pageX; starty = e.touches[0].pageY; }, false); //手指離開螢幕 document.addEventListener("touchend", function(e) { var endx, endy; endx = e.changedTouches[0].pageX; endy = e.changedTouches[0].pageY; var direction = getDirection(startx, starty, endx, endy); switch (direction) { case 0: alert("未滑動!"); break; case 1: alert("向上!") break; case 2: alert("向下!") break; case 3: alert("向左!") break; case 4: alert("向右!") break; default: } }, false);
出處:http://www.haorooms.com/post/webapp_bodyslidebcdiv