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>
相关推荐
雪芽蓝域zzs4 小时前
uniapp 国密sm2加密
uni-app
打不着的大喇叭14 小时前
uniapp的光标跟随和打字机效果
前端·javascript·uni-app
zengzehui15 小时前
uniapp启动图被拉伸问题
uni-app
iOS阿玮17 小时前
AppStore教你一招免备案的骚操作!
uni-app·app·apple
ModyQyW1 天前
用 AI 驱动 wot-design-uni 开发小程序
前端·uni-app
耶啵奶膘2 天前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
耶啵奶膘3 天前
uniapp——地图路线绘制map
uni-app
shadouqi3 天前
uniapp实现图片预览,懒加载,下拉刷新等
uni-app
走,带你去玩3 天前
uniapp 微信小程序水印
微信小程序·小程序·uni-app
菌菇汤3 天前
uni-app实现单选,多选也能搜索,勾选,选择,回显
前端·javascript·vue.js·微信小程序·uni-app·app