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

移动端-模拟手势事件

时间:2017-04-08 16:55:35      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:tar   swipe   pre   mat   rtx   rem   asc   starty   als   

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <style type="text/css">
        .touch-box{
            background-color: #444;
            color:white;
            width: 200px;
            height: 200px;
        }
    </style>
    <div id="touch-box" class="touch-box"></div>
    <script type="text/javascript">
        var bgColors=[‘#BB0D0D‘,‘#189135‘,‘#1173C0‘];
        var idx=0;
        var el=document.getElementById(‘touch-box‘);
        var startX,startY;
        function handleStart(e){
            if(e.touches.length!==1) return

            startX=e.touches[0].pageX;
            startY=e.touches[0].pageY;

            el.addEventListener(‘touchmove‘,handleMove,false);
        }
        function handleMove(e){
            var touches=e.touches;
            if(touches&&touches.length){
                var deltaX=startX-touches[0].pageX;
                var deltaY=startY-touches[0].pageY;
                if(deltaX>50){
                    console.log(‘swipeLeft‘);
                    idx=(idx+1)%3;
                    el.style.backgroundColor=bgColors[idx];
                }
                if(deltaX>-50){
                    console.log(‘swipeRight‘);
                    idx=idx>=1?idx-1:2;
                    el.style.backgroundColor=bgColors[idx];
                }
                if(deltaY>50){
                    console.log(‘swipeTop‘);
                }
                if(deltaY<-50){
                    console.log(‘swipeDown‘)
                }
                if(Math.abs(deltaX)>=50||Math.abs(deltaY)>=50){
                    el.removeEventListener(‘touchmove‘,handleMove);
                }
            }
            event.preventDefault();
        }
        el.addEventListener(‘touchstart‘,handleStart);
    </script>
</body>
</html>

分别取touchstart事件和touchmove事件中事件对象(e.touches[0])的pageX和pageY属性,相减后进行判断,判断之后记得移除touchmove事件

移动端-模拟手势事件

标签:tar   swipe   pre   mat   rtx   rem   asc   starty   als   

原文地址:http://www.cnblogs.com/YutaoZhou/p/6682241.html

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