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阿玮3 小时前
打个广告,帮忙招一个iOS开发的扛把子~
uni-app·app·apple
Cerrda4 小时前
🌟让你的uniapp应用拥有更现代的交互体验,一个支持滚动渐变透明的导航栏组件🌟
uni-app
2501_916007475 小时前
iOS 应用性能测试的工程化流程,构建从指标采集到问题归因的多工具协同测试体系
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张8 小时前
iOS 抓不到包怎么办?从 HTTPS 解密、QUIC 排查到 TCP 数据流分析的完整解决方案
android·tcp/ip·ios·小程序·https·uni-app·iphone
前端互助会8 小时前
UNI-APP开发APP避坑指南:这些关键事项你必须掌握
uni-app
游戏开发爱好者81 天前
iOS 商店上架全流程解析 从工程准备到审核通过的系统化实践指南
android·macos·ios·小程序·uni-app·cocoa·iphone
toooooop81 天前
Vuex 中 state、mutations 和 actions 的原理和写法
前端·javascript·uni-app
林_xi1 天前
uniapp使用@uni-ku/root插件实现全局组件
前端·uni-app
计算机毕设定制辅导-无忧学长1 天前
基于uni-app的“民族风韵”特色购物小程序
uni-app
一个处女座的程序猿O(∩_∩)O1 天前
UniApp 生命周期全解析:从应用到页面,再到组件的完美协奏曲
前端·uni-app