uniapp 实现左滑右滑事件页面跟着滑动

1、绑定事件,主要利用组件的触摸开始、触摸中、触摸结束事件来实现

1
<view  @touchstart="touchStart" @touchend="touchEnd" @touchmove="touchMove" :style="{left: moveX + 'px'}" style="position: relative;"></view>

2、声明初始化点击位置变量 startX、移动的横向距离 moveX

1
2
3
4
5
6
data(){
return {
startX:0,
moveX:0
}
},

3、利用开始触摸和结束触摸的位置的x坐标来判断是左滑还是右滑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 滑动开始
touchStart(e) {
if (e.touches.length == 1) {
//设置触摸起始点水平方向位置
this.startX = e.touches[0].clientX;
}
},
// 滑动中
touchMove(e){
this.moveX = ~~(e.touches[0].clientX - this.startX);
},
// 滑动结束
touchEnd(e) {
if (e.changedTouches.length == 1) {
//手指移动结束后水平位置
var endX = e.changedTouches[0].clientX;
let diff = endX - this.startX;
if (Math.abs(diff) > 20) {
if (diff > 0) {
console.log("左滑...")
this.moveX = 0;
} else {
console.log("右滑...")
this.moveX = 0;
}
}
}
}