ES6类封装判断用户上下左右滑动事件!
2024-08-26 14:00:43
/**
* 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!
最新文章
- ThinkPhp 3.2 数据的连贯操作
- Centos 6.5 部署 redmine 3.3
- [.Net] 通过反射,给Enum加备注
- phonegap 3.3教程 地理信息api教程
- IIS发布报错
- JavaScript函数调用
- DexIndexOverflowException: Cannot merge new index 66080 into a non-jumbo instruction!
- 最短路径floy算法———模板
- app后端设计(0)--总文件夹
- 计算机学院大学生程序设计竞赛(2015’12) 1004 Happy Value
- C++ 设计模式 依赖倒置原则 简单示例
- EXP导出aud$报错EXP-00008,ORA-00904 解决
- Python学习笔记十一
- Openstack oslo.config【一】
- OSPFv3综合实验(GNS3)
- can&#39;t access lexical declaration `a&#39; before initialization
- 【Win10】实现控件倒影效果
- 使用inline-block,使前面img,后面空div居中显示在一行后,导致当div中有内容时,div下移问题
- 【NLP+Deep learning】好文
- 支持FreeMarker需要哪些JAR包?