小程序监听屏幕滑动事件
功能设计背景
功能实现
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'){
//下滑触发操作
}
},
参考