js判断手指滑动(判断手机上下左右屏幕滑动事件)
js判断手指滑动方向(移动端),判断手机屏幕上手指的上滑、下滑、左滑、右滑操作并提示方法1:
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.pageX;
starty = e.touches.pageY;
}, false);
//手指离开屏幕
document.addEventListener("touchend", function(e) {
var endx, endy;
endx = e.changedTouches.pageX;
endy = e.changedTouches.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);
$("body").on("touchstart", function(e) {
e.preventDefault();
startX = e.originalEvent.changedTouches.pageX,
startY = e.originalEvent.changedTouches.pageY;
});
$("body").on("touchmove", function(e) {
e.preventDefault();
moveEndX = e.originalEvent.changedTouches.pageX,
moveEndY = e.originalEvent.changedTouches.pageY,
X = moveEndX - startX,
Y = moveEndY - startY;
if ( X > 0 ) {
//右滑
alert("left 2 right");
}
else if ( X < 0 ) {
//左滑
alert("right 2 left");
}
else if ( Y > 0) {
//下滑
alert("top 2 bottom");
}
else if ( Y < 0 ) {
//上滑
alert("bottom 2 top");
}
else{
alert("just touch");
}
});
页:
[1]