微信小程序事件触发顺序
- 单击: touchstart –> touchend –> tap
- 双击: touchstart –> touchend –> tap –> touchstart –> touchend –> tap
- 长按: touchstart –> longtap –> touchend –> tap
实例代码:
1 2 3
| <view bindtouchstart="bindTouchStart" bindtouchend="bindTouchEnd" bindlongpress="bingLongTap" bindtap="bindTap"> 此处为测试区域 </view>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Page({ bindTouchStart: function (e) { console.log('触摸开始') this.startTime = e.timeStamp; }, bindTouchEnd: function (e) { console.log('触摸结束') this.endTime = e.timeStamp; }, bindTap: function (e) { if (this.endTime - this.startTime < 350) { console.log("点击") } }, bingLongTap: function (e) { console.log("长按"); } })
|
官方的长按事件 bindlongpress 的缺点是长按触发的时间为定值(350ms),时间较短,实际使用中长按效果并不明显。我们可以根据官方给出的 touchstart (触摸开始时间)和 touchend (触摸结束时间)事件,设计可以自定义长按时长的点击事件。
1 2 3 4 5 6 7 8 9 10 11
| Page({ bindTap: function (e) { if (this.endTime - this.startTime < 350) { console.log("点击") } console.log(this.endTime, this.startTime) if (this.endTime - this.startTime >= 1000) { console.log("长按"); } } })
|
如果触摸开始事件与触摸结束事件采取捕获方式,即 catchtouchstart 与 catchtouchend ,那么 bindtap 、 catchtap 、 bindlongpress 、 catchlongpress 事件均无法触发。
此时可以用触摸事件模拟点击或者长按事件,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Page({ bindTouchStart: function (e) { console.log('触摸开始') this.startY = e.changedTouches[0].pageY this.startTime = e.timeStamp; }, bindTouchEnd: function (e) { console.log('触摸结束') this.endTime = e.timeStamp; if (this.endTime - this.startTime < 350) { console.log("点击") } else if (this.endTime - this.startTime >= 1000) { console.log("长按"); } else { let ty = this.startY - e.changedTouches[0].pageY; console.log("触发其他事件", ty); } }, })
|
如果想实现双击事件,可以判断两次单击的时间差小于300ms,双击与单击并存实现,示例代码如下:
1 2 3 4 5 6 7 8
| Page({ bindTap: function (e) { if (e.timeStamp - this.touchStartTime < 300) { console.log("双击") } this.touchStartTime = e.timeStamp } })
|