原生移動端滑動js
阿新 • • 發佈:2019-01-01
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<meta content="yes" name="apple-mobile-web-app-capable" />
<meta content="black" name="apple-mobile-web-app-status-bar-style" />
<meta content="telephone=no" name="format-detection" />
</head>
<body>
<div class="page page1">page1</div>
<div class="page page2"> page2</div>
<div class="page page3">page3</div>
<div class="page page4">page4</div>
</body>
</html>
<script>
// 返回角度
function GetSlideAngle(dx, dy) {
return Math.atan2(dy, dx) * 180 / Math.PI;
}
//根據起點和終點返回方向 1:向上,2:向下,3:向左,4:向右,0:未滑動
function GetSlideDirection(startX, startY, endX, endY) {
var dy = startY - endY;
var dx = endX - startX;
var result = 0;
//如果滑動距離太短
if(Math.abs(dx) < 50 && Math.abs(dy) <50) {
return result;
}
var angle = GetSlideAngle(dx, dy);
if(angle >= -45 && angle < 45) {
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)) {
result = 3;
}
return result;
}
//滑動處理
var startX, startY;
document.addEventListener('touchstart',function (ev) {
startX = ev.touches[0].pageX;
startY = ev.touches[0].pageY;
}, false);
document.addEventListener('touchend',function (ev) {
var endX, endY;
endX = ev.changedTouches[0].pageX;
endY = ev.changedTouches[0].pageY;
var direction = 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:
}
}, false);
</script>