码迷,mamicode.com
首页 > 移动开发 > 详细

移动端判断触摸的方向

时间:2017-06-03 21:47:51      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:star   idt   html   color   ntb   屏幕   math   移动端   back   

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

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

<!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轴的距离相比较来判断的。

移动端判断触摸的方向

标签:star   idt   html   color   ntb   屏幕   math   移动端   back   

原文地址:http://www.cnblogs.com/11lang/p/6938451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!