微信小程序系列 -- 触摸滑动事件

微信小程序通过三个事件共同作用实现了触摸滑动事件,即 bingtouchstartbindtouchmovebindtouchend 事件。

WXML:

<view class='btn'  bindtouchstart='touchStart' bindtouchmove='touchMove' bindtouchend='touchEnd'>
OK
</view>

JS:

  data: {
    touchS : [0,0],
    touchE : [0,0]
  },

  touchStart: function(e){
    // console.log(e.touches[0].pageX)
    let sx = e.touches[0].pageX
    let sy = e.touches[0].pageY
    this.data.touchS = [sx,sy]
  },
  touchMove: function(e){
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchE = [sx, sy]
  },
  touchEnd: function(e){
    let start = this.data.touchS
    let end = this.data.touchE
    console.log(start)
    console.log(end)
    if(start[0] < end[0] - 50){
      console.log('右滑')
    }else if(start[0] > end[0] + 50){
      console.log('左滑')
    }else{
      console.log('静止')
    }
  },

在 touchstart 时,监听到触摸开始时的 (x, y)位置;在 touchMove 方法中持续监听触摸点的位置(x, y),并保存在 data 中;在 touchEnd 方法中对开始的触摸位置和结束的触摸位置进行判断,如果移动距离大于 50 则判定为发生触摸滑动事件。

在上面示例中,当 X 轴方向的移动超过 50 时即判定为左滑或右滑,相应的也可以通过判断 Y 轴方向的滑动长度,来判断上滑或是下滑,由此实现触摸滑动的功能。

更多信息联系我的微信公众号 「大学IT圈」
在这里插入图片描述

  • 19
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
微信小程序中有许多滑动事件可以使用,以下是常用的几个: 1. touchstart:手指触摸屏幕触发的事件。 2. touchmove:手指在屏幕上滑动触发的事件。 3. touchend:手指离开屏幕触发的事件。 4. touchcancel:手指触摸屏幕后被其它事件打断,如来电提醒、弹窗等触发的事件。 5. swipe:手指在屏幕上快速滑动触发的事件。 6. scroll:滚动页面触发的事件。 使用这些滑动事件,你可以实现许多交互效果。例如,你可以使用touchstart、touchmove和touchend事件来实现拖拽效果;使用swipe事件来实现滑动删除、左右滑动切换页面等效果;使用scroll事件来实现上下滚动页面时的特效等等。 以下是一个示例代码,实现了在屏幕上滑动手指时,页面中的一个元素会跟着手指移动: ``` <view class="container" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd"> <view class="ball" style="left: {{ballLeft}}px; top: {{ballTop}}px;"></view> </view> Page({ data: { ballLeft: 0, ballTop: 0, startX: 0, startY: 0 }, touchStart: function(e) { this.setData({ startX: e.touches[0].clientX, startY: e.touches[0].clientY }); }, touchMove: function(e) { var diffX = e.touches[0].clientX - this.data.startX; var diffY = e.touches[0].clientY - this.data.startY; this.setData({ ballLeft: this.data.ballLeft + diffX, ballTop: this.data.ballTop + diffY, startX: e.touches[0].clientX, startY: e.touches[0].clientY }); }, touchEnd: function(e) { // do something } }); ``` 在这个示例中,我们使用了touchstart、touchmove和touchend事件来实现元素的拖拽效果。当手指在屏幕上滑动时,ball元素的位置会随之改变。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值