文章目錄
  1. 找到触摸之前横纵坐标
  2. 找到触摸之后横纵坐标
  3. 相减得到滑动的距离,如果横着长度大于竖着长度,就是左右滑动,再根据正负可以判断是左还是右,反之,同理可得,是上还是下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    <!DOCTYPE html>
    <html>
    <head lang="en">
    <meta charset="UTF-8">
    <title>判断滑动方向</title>
    </head>
    <style>
    html{
    height: 100%;
    }

    body{
    height: 100%;
    background-color: #f47500;
    }

    </style>

    <body>

    </body>
    <script>
    var touchStartClientX,touchStartClientY, direction;
    document.addEventListener('touchstart',function(e){
    touchStartClientX= e.touches[0].clientX;
    touchStartClientY=e.touches[0].clientY;
    //console.log(touchStartClientX+','+touchStartClientY);
    })
    document.addEventListener('touchend',function(e){
    var touchendClientX,touchendClientY;
    touchendClientX= e.changedTouches[0].clientX;
    touchendClientY=e.changedTouches[0].clientY;
    //console.log(touchendClientX+','+touchendClientY);
    var sx=touchendClientX-touchStartClientX;
    var sy=touchendClientY-touchStartClientY;
    console.log(sx+','+sy);
    /* if(Math.abs(sx)>Math.abs(sy)){
    if(sx>0)
    direction='right';
    else
    direction='left';
    }else{
    if(sy>0)
    direction='down';
    else
    direction='up';
    }*/

    direction=Math.abs(sx)>Math.abs(sy)?(sx>0?'right':'left'):(sy>0?'down':'up');
    alert('direction='+direction);
    })
    </script>

    </html>

效果预览:http://output.jsbin.com/wuqilofoyi 需要谷歌浏览器模拟一下手机看

文章目錄