移动端滑动方向判断,主要是判断利用x,y轴方向的增量,哪个轴增的快,就是哪个方向。
在touchstart中获取初始点,startX, startY;
在touchmove中获取移动点,moveX, moveY
计算两者的差 deltaX = moveX - startX; deltaY = moveY - startY;
之后累加deltaX和deltaY:
distX += Math.abs(deltaX)
distY += Math.abs(deltaY)
if (distX > distY && deltaX > 0) {
console.log(‘右滑‘)
}
if (distX > distY && deltaX < 0) {
console.log(‘左滑‘)
}
if (distX < distY && deltaY < 0) {
console.log(‘上滑‘)
}
if (distX < distY && deltaY > 0) {
console.log(‘下滑‘)
}
思路就是这样,代码如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>滑动方向判断</title> <style> #box{ width: 100%; height: 500px; background: orange; } </style> </head> <body> <div id="box"></div> <script> let startX,startY,moveX,moveY,deltaX,deltaY; let distX = 0 let distY = 0 let box = document.getElementById(‘box‘) box.addEventListener(‘touchstart‘, function(e) { let point = e.touches ? e.touches[0] : e startX = point.pageX startY = point.pageY distX = 0 distY = 0 }) box.addEventListener(‘touchmove‘, function(e) { let point = e.touches ? e.touches[0] : e moveX = point.pageX moveY = point.pageY deltaX = moveX - startX deltaY = moveY - startY distX += Math.abs(deltaX) distY += Math.abs(deltaY) console.log(distX, distY) if (distX > distY && deltaX > 0) { console.log(‘右滑‘) } if (distX > distY && deltaX < 0) { console.log(‘左滑‘) } if (distX < distY && deltaY < 0) { console.log(‘上滑‘) } if (distX < distY && deltaY > 0) { console.log(‘下滑‘) } }) </script> </body> </html>
原文地址:https://www.cnblogs.com/lonfate/p/9157327.html
时间: 2024-10-06 23:21:38