1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| var startx, starty;
function getAngle(angx, angy) { return Math.atan2(angy, angx) * 180 / Math.PI; };
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);
|