小程序監聽屏幕滑動事件
功能設計背景
- 小程序頁面點擊事件的坐標系是以左下角為原點的直角坐標系。
- 微信小程序提供
bindtouchstart
和bindtouchend
接口用於監聽觸點的變化。
功能實現
1.在你需要監聽的塊外增加監聽遮罩層,包含待監聽塊在內
<view bindtouchstart="touchStart" bindtouchend="touchEnd">
<!--待監聽功能模塊-->
</view>
2.根據觸點的起始位置和終止位置計算滑動方向(在data中配置touchx
和touchy
數值)
touchStart(e) {
console.log(e)
var that = this;
that.setData({
touchx: e.changedTouches[0].clientX,
touchy: e.changedTouches[0].clientY
})
},
touchEnd(e) {
console.log(e)
var that = this;
let x = e.changedTouches[0].clientX;
let y = e.changedTouches[0].clientY;
let turn = "";
if (x - that.data.touchx > 50 && Math.abs(y - that.data.touchy) < 50) { //右滑
turn = "right";
} else if (x - that.data.touchx < -50 && Math.abs(y - that.data.touchy) < 50) { //左滑
turn = "left";
}
if(y - that.data.touchy > 50 && Math.abs(x - that.data.touchx) < 50){ //下滑
turn = "down";
}else if(y - that.data.touchy < -50 && Math.abs(x - that.data.touchx) < 50){ //上滑
turn="up";
}
//根據方向進行操作
if(turn == 'down'){
//下滑觸發操作
}
},
參考