首先给盒子绑定touch事件(我用的是react,vue其实也差不多了)。
<View
onTouchStart={e => this.touchStart(e)}
onTouchMove={(e) => this.touchMove(e)}
onTouchEnd={(e) => this.touchEnd(e)}
>
......
</View>
通过记录下滑动开始的位置以及滑动结束的位置,来计算手指滑动的方向。
class BackQuery extends Component {
constructor(props) {
super(props);
this.state = {
touchStart: [0, 0],
touchMove: [0, 0],
};
}
// 触摸开始事件
touchStart = e => {
let sx = e.touches[0].pageX;
let sy = e.touches[0].pageY;
const touchStart = [sx, sy];
this.setState({ touchStart });
};
// 触摸滑动事件
touchMove = e => {
let sx = e.touches[0].pageX;
let sy = e.touches[0].pageY;
const touchMove = [sx, sy];
this.setState({ touchMove });
};
// 触摸结束事件
touchEnd = () => {
const { touchStart, touchMove} = this.state;
if (touchMove[0] === 0) return;
if (touchStart[0] - touchMove[0] > 0) {
console.log("向左滑,这里可以调用方法,及页面跳转事件");
} else if (touchStart[0] - touchMove[0] < 0) {
console.log("向右滑,这里可以调用方法,及页面跳转事件");
} else {
console.log("向上或向下滑动");
}
this.setState({ touchMove: [0, 0] });
};
可以通过navigator.userAgent来获取客户端类型juejin.cn/post/717430…