问题描述
当你使用hammerjs为一个元素绑定滑动事件(swipeup, swipedown, swipeleft, swiperight)以后,如果该元素内部包含图片元素就会出现异常:手指在图片上进行滑动并不会出发父元素的滑动事件。
解决办法
禁止图片的touchmove事件: e.preventDefault(),还可以根据滑动方向分别作处理,代码如下:
<img @touchstart="touchstartHandler" @touchmove="touchmoveHandler" src="..." alt="">
touchstartHandler(e) {
this.startX = e.touches[0].pageX;
this.startY = e.touches[0].pageY;
}
touchmoveHandler(e) {
let moveEndX = e.changedTouches[0].pageX;
let moveEndY = e.changedTouches[0].pageY;
let x = moveEndX -this.startX;
let y = moveEndY -this.startY;
if ( Math.abs(x) > Math.abs(y) && x >0 ) { // right
console.log('向右');
} else if ( Math.abs(x) > Math.abs(y) && x <0 ) { // left
console.log('向左');
} else if ( Math.abs(y) > Math.abs(x) && y >0) { // down
e.preventDefault();
} else if ( Math.abs(y) > Math.abs(x) && y <0 ) { // up
e.preventDefault();
} else {// 没有发生滑动
console.log('没有发生滑动');
}
}