首页 > 代码库 > 移动端-模拟手势事件

移动端-模拟手势事件

<!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事件

移动端-模拟手势事件