用生命谱写代码的赞歌

0%

微信小程序点击/滑动事件冲突解决方式

微信小程序事件触发顺序

  1. 单击: touchstart –> touchend –> tap
  2. 双击: touchstart –> touchend –> tap –> touchstart –> touchend –> tap
  3. 长按: 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) // 只有在未触发longpress长按的情况下才能出发后续点击事件
if (this.endTime - this.startTime >= 1000) {
console.log("长按");
}
}
})

如果触摸开始事件与触摸结束事件采取捕获方式,即 catchtouchstartcatchtouchend ,那么 bindtapcatchtapbindlongpresscatchlongpress 事件均无法触发。

此时可以用触摸事件模拟点击或者长按事件,示例代码如下:

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;
// 判断 ty 移动的距离触发其他事件
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
}
})