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>
相关推荐
anyup2 小时前
🔥🔥 10 天 Star 破百!uView Pro 文档也开源啦:完全免费、无广告、高效上手
前端·vue.js·uni-app
fakaifa12 小时前
【最新版】CRMEB Pro版v3.4系统源码全开源+PC端+uniapp前端+搭建教程
人工智能·小程序·uni-app·php·crmeb·源码下载·crmebpro
2501_9159184119 小时前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
梦里寻码1 天前
自行食用 uniapp 多端 手写签名组件
前端·uni-app
不如摸鱼去2 天前
Trae 辅助下的 uni-app 跨端小程序工程化开发实践分享
微信小程序·小程序·uni-app·aigc·ai编程
小白_ysf2 天前
uniapp 开发微信小程序,获取经纬度并且转化详细地址(单独封装版本)
微信小程序·uni-app
iOS阿玮2 天前
三年期已满,你的产品不再更新将于90天后下架。
uni-app·app·apple
bug总结3 天前
深入理解 uni-app 的 uni.createSelectorQuery()
uni-app
真上帝的左手3 天前
25. 移动端-uni-app
uni-app
编程猪猪侠3 天前
基于Uni-app+vue3实现微信小程序地图固定中心点范围内拖拽选择位置功能(分步骤详解)
uni-app