准备下面几个函数
moveListenerStartup() {
var el = document.getElementsByTagName("body")[0];
el.addEventListener("touchstart", this.handleStart, false);
el.addEventListener("touchend", this.handleEnd, false);
},
handleStart: function(e) {
const that = this;
that.startX = e.touches[0].pageX;
that.startY = e.touches[0].pageY;
e = e || window.event;
},
handleEnd(e) {
const that = this;
that.endX = e.changedTouches[0].pageX;
that.endY = e.changedTouches[0].pageY;
that.upOrDown(that.startX, that.startY, that.endX, that.endY);
},
upOrDown(startX, startY, endX, endY) {
const that = this;
let direction = that.GetSlideDirection(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:
break;
}
},
//根据起点和终点返回方向 1:向上,2:向下,3:向左,4:向右,0:未滑动
GetSlideDirection(startX, startY, endX, endY) {
const that = this;
let dy = startY - endY;
let dx = endX - startX;
let result = 0;
//如果滑动距离太短
if (Math.abs(dx) > 50 || Math.abs(dy) > 5) {
} else {
return result;
}
let angle = that.GetSlideAngle(dx, dy);
if (angle >= -45 && angle < 45) {
if (Math.abs(dx) > 50) {
result = 4;
}
} else if (angle >= 45 && angle < 135) {
result = 1;
} else if (angle >= -135 && angle < -45) {
result = 2;
} else if (
(angle >= 135 && angle <= 180) ||
(angle >= -180 && angle < -135)
) {
if (Math.abs(dx) > 50) {
result = 3;
}
}
return result;
},
//返回角度
GetSlideAngle(dx, dy) {
return (Math.atan2(dy, dx) * 180) / Math.PI;
}
页面初始化完成后,调用
this.moveListenerStartup() //初始化滑动监听