有一个项目需求是,打开小程序,手指在屏幕上右滑唤醒菜单,左滑关闭菜单。需要监听手势动作,废话少说直接上代码
1.需要在dom上先绑定监听事件,监听手势滑动 @touchstart="touchStart" @touchend="touchEnd" @touchcancel="touchCancel" 如图,在最外层标签绑定事件
2.在js里写事件
//写在data里
minOffset: 50, //最小偏移量,低于这个值不响应滑动处理
minTime: 60, // 最小时间,单位:毫秒,低于这个值不响应滑动处理
startX: 0, //开始时的X坐标
startY: 0, //开始时的Y坐标
startTime: 0, //开始时的毫秒数
animationData: {},
//写在方法里
touchStart(e) {
this.startX = e.touches[0].pageX; // 获取触摸时的x坐标
this.startY = e.touches[0].pageY; // 获取触摸时的x坐标
this.startTime = new Date().getTime(); //获取毫秒数
},
touchCancel: function (e) {
this.startX = 0; //开始时的X坐标
this.startY = 0; //开始时的Y坐标
this.startTime = 0; //开始时的毫秒数
},
touchEnd: function (e) {
var that = this;
var endX = e.changedTouches[0].pageX;
var endY = e.changedTouches[0].pageY;
var touchTime = new Date().getTime() - this.startTime; //计算滑动时间
//1.判断时间是否符合
if (touchTime >= this.minTime) {
//2.判断偏移量:分X、Y
var xOffset = endX - this.startX;
var yOffset = endY - this.startY;
//①条件1(偏移量x或者y要大于最小偏移量)
//②条件2(可以判断出是左右滑动还是上下滑动)
if (Math.abs(xOffset) >= Math.abs(yOffset) && Math.abs(xOffset) >= this.minOffset) {
//左右滑动
//③条件3(判断偏移量的正负)
if (xOffset < 0) {
console.log('向左滑动')
} else {
console.log('向右滑动')
}
} else if (Math.abs(xOffset) < Math.abs(yOffset) && Math.abs(yOffset) >= this.minOffset) {
//上下滑动
//③条件3(判断偏移量的正负)
if (yOffset < 0) {
// console.log('向上滑动')
} else {
// console.log('向下滑动')
}
}
} else {
// console.log('滑动时间过短', touchTime)
}
},