Skip to content

使用触摸事件判断滑动方向 #9

Open
@raclen

Description

@raclen
  1. 找到触摸之前横纵坐标
  2. 找到触摸之后横纵坐标
  3. 相减得到滑动的距离,如果横着长度大于竖着长度,就是左右滑动,再根据正负可以判断是左还是右,反之,同理可得,是上还是下
<!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 需要谷歌浏览器模拟一下手机看

#2015-08-28

Metadata

Metadata

Assignees

No one assigned

    Labels

    博客搬迁以前博客的文章迁移过来

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions