uniapp小程序怎么判断滑动的方向

项目场景:

获取手机上手指滑动的距离超过一定距离 来操作一些逻辑


解决方案:

在uniapp中,可以通过监听触摸事件来判断滑动的方向。常用的触摸事件包括touchstart, touchmove, 和 touchend。通过这些事件的参数,可以计算出用户的滑动起点和终点,进而判断滑动方向

touchStart 方法记录了触摸开始时的坐标,touchMove 方法在触摸移动时更新了坐标,touchEnd 方法则在触摸结束时计算出滑动的方向。getSwipeDirection 方法用于根据起点和终点的坐标判断出水平或垂直方向的滑动,如果水平方向的位移大于阈值,则判定为水平滑动;如果垂直方向的位移大于阈值,则判定为垂直滑动。

html 复制代码
<template>
  <view @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
    <!-- 滑动区域内容 -->
    <view 
        v-for="(item,index) in 20" 
        :key="index" 
        style="border:1rpx solid #ccc;height:100rpx">
        测试11111
    </view>
  </view>
</template>
 
<script>
export default {
  data() {
    return {
      startX: 0, // 触摸开始的X坐标
      startY: 0, // 触摸开始的Y坐标
      endX: 0,   // 触摸结束的X坐标
      endY: 0,   // 触摸结束的Y坐标
    };
  },
  methods: {
    touchStart(event) {
      this.startX = event.touches[0].pageX;
      this.startY = event.touches[0].pageY;
    },
    touchMove(event) {
      // 移动时更新结束坐标
      this.endX = event.touches[0].pageX;
      this.endY = event.touches[0].pageY;
    },
    touchEnd(event) {
      let direction = this.getSwipeDirection(
        this.startX, this.startY, this.endX, this.endY
        );
      console.log('Swipe direction: ' + direction);
    },
    getSwipeDirection(startX, startY, endX, endY) {
      const threshold = 30; // 设定一个阈值,用于判断是否是滑动
      const deltaX = endX - startX;
      const deltaY = endY - startY;
 
      // 如果水平方向的位移大于垂直方向,且水平方向的位移大于阈值,则认为是水平滑动
      if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > threshold) {
        return deltaX > 0 ? 'right' : 'left';
      }
      // 如果垂直方向的位移大于水平方向,且垂直方向的位移大于阈值,则认为是垂直滑动
      else if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > threshold) {
        return deltaY > 0 ? 'down' : 'up';
      }
      // 其他情况视为无效滑动
      return 'none';
    },
  },
};
</script>
相关推荐
iOS阿玮2 小时前
“死了么”App荣登付费榜第一名!
uni-app·app·apple
wendycwb6 小时前
uni-app 在真机中canvas绘制的元素悬浮,内容不随父组件滚动问题
uni-app
frontend_frank7 小时前
脱离 Electron autoUpdater:uni-app跨端更新:Windows+Android统一实现方案
android·前端·javascript·electron·uni-app
三天不学习8 小时前
UniApp三端实时通信实战:SignalR在H5、APP、小程序的差异与实现
微信小程序·uni-app·signalr
念你那丝微笑8 小时前
uView Plus + Vue3 + TypeScript + UniApp 正确引入 UnoCSS(避坑版)
vue.js·typescript·uni-app
念你那丝微笑9 小时前
vue3+ts在uniapp项目中实现自动导入 ref 和 reactive
vue.js·typescript·uni-app
游戏开发爱好者89 小时前
如何使用 AppUploader 提交上传 iOS 应用
android·ios·小程序·https·uni-app·iphone·webview
iOS阿玮1 天前
AppStore卡审依旧存在,预计下周将逐渐恢复常态!
uni-app·app·apple
郑州光合科技余经理1 天前
开发实战:海外版同城o2o生活服务平台核心模块设计
开发语言·git·python·架构·uni-app·生活·智慧城市
行走的陀螺仪1 天前
在UniApp H5中,实现路由栈的持久化
前端·javascript·uni-app·路由持久化·路由缓存策略