移动端判断触摸的方向

最近做微信端页面,于是趁周末梳理了下移动端的事件这一块。

通过判断手指在屏幕上移动的位置减去手指放在屏幕上时的位置,就可以得出是往什么方向滑动:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        div{
            position: relative;
            width: 500px;
            height: 500px;
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div id="d"></div>
    <script type="text/javascript">
        var d = document.getElementById('d'),
            startX,startY,moveX,moveY;

        d.addEventListener('touchstart',function(e){
            var target = e.targetTouches[0];
            startX = target.clientX,
            startY = target.clientY;
        });

        d.addEventListener('touchmove',function(e){
            var target = e.targetTouches[0];
            moveX = target.clientX;
            moveY = target.clientY;

            var x = moveX - startX,
                y = moveY - startY;

            // 如果x>0并且x轴上移动的距离大于y轴上移动的距离
            if(Math.abs(x) > Math.abs(y) && x > 0){
                alert('向右');
            }
            else if(Math.abs(x) > Math.abs(y) && x < 0){
                alert('向左');
            }
            else if(Math.abs(x) < Math.abs(y) && y > 0){
                alert('向下');
            }
            else if(Math.abs(x) < Math.abs(y) && x < 0){
                alert('向上');
            }
        });

    </script>
</body>
</html>

这里是通过计算得出来的x轴的距离跟y轴的距离相比较来判断的。

posted @ 2017-06-03 20:56  _Jo  阅读(625)  评论(0编辑  收藏  举报