移動web JavaScript手指滑動事件的封裝(touchstart,touchmove,touchend)



demo.html:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Document</title>  
    <style>  
        html,body {  
            height: 100%;  
        }  
  
        .box {  
            height: 80px;  
            width: 80px;  
            border: 1px solid #000;  
            background-color: red;  
        }  
  
    </style>  
</head>  
<body>  
    <div class="box"></div>  
  
    <script>  
        window.onload = function() {  
            var box = document.querySelector(".box");  
            var startX = 0;    //  手指開始滑動的位置  
            var startY = 0;  
            var distanceX = 0;   // 手指總共滑動的距離(滑動距離的疊加)  
            var distanceY = 0;    
            var moveX = 0;  // 手指滑動的距離  
            var moveY = 0;  
  
            document.body.addEventListener("touchstart",function(event) {  
                startX = event.touches[0].clientX;  
                startY = event.touches[0].clientY;                  
            });  
  
            document.body.addEventListener("touchmove",function(event) {  
                moveX = event.touches[0].clientX - startX;  
                moveY = event.touches[0].clientY - startY;  
                box.style.transform = "translate("+ (distanceX+moveX) +"px,"+(distanceY+moveY)+"px)";  // 根據移動距離進行偏移  
            });  
  
            document.body.addEventListener("touchend",function(event) {  
                distanceX = distanceX + moveX;   //  記錄/更新手指總共滑動的距離  
                distanceY = distanceY + moveY;  
            });  
        }  
  
    </script>  
</body>  
</html>





注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com