uniapp微信小程序监听手势动作

有一个项目需求是,打开小程序,手指在屏幕上右滑唤醒菜单,左滑关闭菜单。需要监听手势动作,废话少说直接上代码

1.需要在dom上先绑定监听事件,监听手势滑动 @touchstart="touchStart" @touchend="touchEnd"  @touchcancel="touchCancel" 如图,在最外层标签绑定事件

2.在js里写事件

//写在data里
    minOffset: 50, //最小偏移量,低于这个值不响应滑动处理
    minTime: 60, // 最小时间,单位:毫秒,低于这个值不响应滑动处理
    startX: 0, //开始时的X坐标
    startY: 0, //开始时的Y坐标
    startTime: 0, //开始时的毫秒数
    animationData: {},


//写在方法里

touchStart(e) {
      this.startX = e.touches[0].pageX; // 获取触摸时的x坐标
      this.startY = e.touches[0].pageY; // 获取触摸时的x坐标
      this.startTime = new Date().getTime(); //获取毫秒数
},
touchCancel: function (e) {
      this.startX = 0; //开始时的X坐标
      this.startY = 0; //开始时的Y坐标
      this.startTime = 0; //开始时的毫秒数
},
touchEnd: function (e) {
      var that = this;
      var endX = e.changedTouches[0].pageX;
      var endY = e.changedTouches[0].pageY;
      var touchTime = new Date().getTime() - this.startTime; //计算滑动时间
      //1.判断时间是否符合
      if (touchTime >= this.minTime) {
        //2.判断偏移量:分X、Y
        var xOffset = endX - this.startX;
        var yOffset = endY - this.startY;
        //①条件1(偏移量x或者y要大于最小偏移量)
        //②条件2(可以判断出是左右滑动还是上下滑动)
        if (Math.abs(xOffset) >= Math.abs(yOffset) && Math.abs(xOffset) >= this.minOffset) {
          //左右滑动
          //③条件3(判断偏移量的正负)
          if (xOffset < 0) {
            console.log('向左滑动')
          } else {
            console.log('向右滑动')
            
          }
        } else if (Math.abs(xOffset) < Math.abs(yOffset) && Math.abs(yOffset) >= this.minOffset) {
          //上下滑动
          //③条件3(判断偏移量的正负)
          if (yOffset < 0) {
            // console.log('向上滑动')
          } else {
            // console.log('向下滑动')
          }
        }
      } else {
        // console.log('滑动时间过短', touchTime)
      }
},

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值