微信小程序-防止多次点击跳转的问题
最近多个小程序项目遇到一个头大的问题,就是点击事件多次点击会造成多次重复跳转或多次请求的情况,网上看了一下论坛一大堆方法,试了几个都是不行,最后看了一下小程序的文档,发现遗忘了很实用了触控事件bindtouchstart和bindtouchend。虽然是很好用但是也会存在很多坑,微信小程序开发过程中bindtap事件与bindtouchstart和bindtouchend事件也会存在冲突,一定要注意tap,touchstart,touchend的事件触发顺序为start→end→tap。
废话不多说直接进入代码
<view class='rz-btn' bindtap='rlrzClick' bindtouchstart="touchStart" bindtouchend="touchEnd">立即认证</view>
//一定要注意顺序start→end→tap
Page({
data: {
touchStartTime: 0, // 触摸开始时间
touchEndTime: 0, // 触摸结束时间
lastTapTime: 0 // 最后一次单击事件点击发生时间
},
// 防止重复点击
touchStart(e) {
this.data.touchStartTime = e.timeStamp;
console.log(e);
console.log(this.data.touchStartTime);
},
touchEnd(e) {
this.data.touchEndTime = e.timeStamp;
},
rlrzClick(e) {
// 控制点击事件在350ms内触发,加这层判断是为了防止长按时会触发点击事件
if (this.data.touchEndTime - this.data.touchStartTime < 350) {
// 当前点击的时间
var currentTime = e.timeStamp;
var lastTapTime = this.data.lastTapTime;
// 更新最后一次点击时间
this.data.lastTapTime = currentTime;
// 如果两次点击时间在300毫秒内,则认为是双击事件
if (currentTime - lastTapTime > 300) {
//这里面就放你需要防止多次点击的逻辑或者函数
this.btn()
}
}
}
})
以上就是全部的代码,希望能帮助到遇到同样问题的朋友。如果有更好解决办法的朋友,欢迎在下方留言交流。