Happy New Year!

移动端touch滑动事件监听

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript判断手指在移动端上滑动的方向</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
请在移动端,PC上无法查看效果,滑动查看效果<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;
}, false);
//手指离开屏幕
document.addEventListener("touchend", function(e) {
    var endx, endy;
    endx = e.changedTouches[0].pageX;
    endy = e.changedTouches[0].pageY;
    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:
    }
}, false);
</script>
</body>
</html>

 

文章出自:https://blog.csdn.net/qq_39198420/article/details/76502267;

posted @ 2018-12-05 16:40  一只看夕阳的猫  阅读(3215)  评论(8编辑  收藏  举报
返回顶部小火箭
世界很公平,想要最好,就一定得付出!
x
博客主页