触控获取坐标判断滑动方向

var startx,starty,endx,endy;
// 开始触控的时候绑定touchstart事件
document.addEventListener('touchstart', function(e){
    startx=e.touches[0].pageX;  //获取触摸的X坐标。touches数组保存着多点触控的信息,这里只有一个点,所以为0
    starty=e.touches[0].pageY;
});
//上下滑动的时候可能是触发默认的滚屏事件,从而产生BUG,需要阻止此事件
document.addEventListener('touchmove',function(e){
    e.preventDefault();
});
//结束触控的时候绑定touchend事件
document.addEventListener('touchend', function(e){
    endx=e.changedTouches[0].pageX;  //changedTouches为手指离开的信息
    endy=e.changedTouches[0].pageY;
    var deltax=endx-startx;  //取得触控后坐标的差值
    var deltay=endy-starty;
    if (Math.abs(deltax)<0.3*documentW&&Math.abs(deltay)<0.3*documentW) {  //如果移动的距离小于0.3*设备宽度,则判定为不是滑动,退出(可以避免用户只是普通的点击造成的BUG)
        return;
    }
    if (Math.abs(deltax)>=Math.abs(deltay)) {  //如果为true,则说明这个滑动是在X轴方向
        if (deltax>0) {  //为true则为向右滑动

        }else{  //向左滑动

        }
    }else{
        if (deltay>0) {  //为true则向下滑动

        }else{  //向上滑动

        }
    }
});
原文地址:https://www.cnblogs.com/3body/p/5417051.html