在實際應用中,當某種手勢被觸發后,在用戶沒有放開鼠標或手指前,會一直識別為該手勢。比如當用戶觸發左滑手勢后,這時再向下滑動,仍要按照左滑手勢來處理。
可以定義一個標記來記錄第一次識別到的手勢,如果已識別出手勢,后續的滑動操作就可以忽略,直到用戶放開鼠標或手指。放開鼠標或手指操作可以通過綁定handletouchend事件來處理。
Page({
data: {
lastX: 0,
lastY: 0,
text : "沒有滑動",
currentGesture: 0,
},
handletouchmove: function(event) {
console.log(event)
if (this.data.currentGesture != 0){
return
}
let currentX = event.touches[0].pageX
let currentY = event.touches[0].pageY
let tx = currentX - this.data.lastX
let ty = currentY - this.data.lastY
let text = ""
//左右方向滑動
if (Math.abs(tx) > Math.abs(ty)) {
if (tx < 0) {
text = "向左滑動"
this.data.currentGesture = 1
}
else if (tx > 0) {
text = "向右滑動"
this.data.currentGesture = 2
}
}
//上下方向滑動
else {
if (ty < 0){
text = "向上滑動"
this.data.currentGesture = 3
}
else if (ty > 0) {
text = "向下滑動"
this.data.currentGesture = 4
}
}
//將當前坐標進行保存以進行下一次計算
this.data.lastX = currentX
this.data.lastY = currentY
this.setData({
text : text,
});
},
handletouchtart:function(event) {
console.log(event)
this.data.lastX = event.touches[0].pageX
this.data.lastY = event.touches[0].pageY
},
handletouchend:function(event) {
console.log(event)
this.data.currentGesture = 0
this.setData({
text : "沒有滑動",
});
},
})
