Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
raclen opened this issue Sep 15, 2019 · 0 comments
Open

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

raclen opened this issue Sep 15, 2019 · 0 comments
Labels
博客搬迁 以前博客的文章迁移过来

Comments

@raclen
Copy link
Owner

raclen commented Sep 15, 2019

  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

@raclen raclen added the 博客搬迁 以前博客的文章迁移过来 label Sep 15, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
博客搬迁 以前博客的文章迁移过来
Projects
None yet
Development

No branches or pull requests

1 participant