- 监听
touchstart
、touchend
事件
- 获取
touches[0].pageX/Y
和 changedTouches[0]
差值
- 计算角度(斜向上,斜向下、等待)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.container {
width: 100%;
height: 500px;
background-color: pink;
}
</style>
</head>
<body>
<div class="container"></div>
<script>
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[0].pageX;
starty = e.touches[0].pageY;
console.log(e.touches);
},
false
);
//手指离开屏幕
document.addEventListener(
"touchend",
function (e) {
var endx, endy;
endx = e.changedTouches[0].pageX;
endy = e.changedTouches[0].pageY;
console.log(e.changedTouches, e.touches);
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:
alert("点击!");
break;
}
},
false
);
</script>
</body>
</html>