以下是一个示例代码,演示如何在微信小程序中监听用户的左滑、右滑和上滑手势:
1 | {{gesture}} |
1 2 3 4 5 6 7 8 9 10 11 12 | .container { width : 100% ; height : 100 vh; display : flex; align-items : center ; justify-content : center ; } .gesture-text { font-size : 20px ; text-align : center ; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | Page({ data: { startX: 0, // 滑动起始点横坐标 startY: 0, // 滑动起始点纵坐标 gesture: '' , // 手势 }, touchStart: function (e) { this .setData({ startX: e.touches[0].clientX, startY: e.touches[0].clientY, }) }, touchMove: function (e) { const startX = this .data.startX const startY = this .data.startY const diffX = e.touches[0].clientX - startX const diffY = e.touches[0].clientY - startY if (Math.abs(diffX) > Math.abs(diffY)) { // 左滑 if (diffX 40) { this .setData({ gesture: '右滑' , }) } } else { // 上滑 if (diffY < -40) { this .setData({ gesture: '上滑' , }) } } }, touchEnd: function () { this .setData({ gesture: '' , }) }, }) |
在上述代码中,我们在一个容器 container
上绑定了 bindtouchstart
、bindtouchmove
和 bindtouchend
事件,分别用于监听用户的触摸开始、移动和结束操作。在触摸开始时,我们记录下起始点的横纵坐标。在触摸移动时,我们计算出横向和纵向位移量,并根据位移量判断用户的手势类型。如果横向位移量大于纵向位移量,并且超过一定的阈值(这里设置为 40),则判断为左滑或右滑手势;如果纵向位移量大于横向位移量,并且超过一定的阈值,则判断为上滑手势。最后,在触摸结束时,将手势类型重置为空字符串。