/** * param 原生js方式实现判断用户的滑动方向 * 返回1 向上 * 返回2 向下 * 返回3 向左 * 返回4 向右 */ class juedgeSlide { constructor() { this.startx = ''; this.starty = ''; } //获得角度 getAngle(angx, angy) { return Math.atan2(angy, angx) * 180 / Math.PI; }; //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动 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 = this.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; } // 初始化函数 init(callback) { var that = this; //手指接触屏幕 document.addEventListener("touchstart", function (e) { that.startx = e.touches[0].pageX; that.starty = e.touches[0].pageY; }, false); document.addEventListener("touchmove", function (e) { var endx, endy; endx = e.changedTouches[0].pageX; endy = e.changedTouches[0].pageY; var direction = that.getDirection(that.startx, that.starty, endx, endy); callback(direction, true); }, false); //手指离开屏幕 document.addEventListener("touchend", function (e) { var endx, endy; endx = e.changedTouches[0].pageX; endy = e.changedTouches[0].pageY; var direction = that.getDirection(that.startx, that.starty, endx, endy); callback(direction, false); }, false); }
}
说明:引入改类后,调用init方法,然后在回调函数里面判断返回的数字,
* 返回1 向上 * 返回2 向下 * 返回3 向左 * 返回4 向右
进而来判断用户滑动的方向!
同时,如果第二个参数返回的是true,代表的是向某个滑动方向滑动进行时,即touchmove!