手勢的條件
1. 必須滑動過
2. 滑動的距離50px
window.onload = function () {
var bindSwipeEvent = function (dom,leftCallback,rightCallback) {
var isMove = false;
var startX = 0;
var distanceX = 0;
dom.addEventListener('touchstart',function (e) {
startX = e.touches[0].clientX;
});
dom.addEventListener('touchmove',function (e) {
isMove = true;
var moveX = e.touches[0].clientX;
distanceX = moveX - startX;
});
dom.addEventListener('touchend',function (e) {
/*滑動結束、判斷是否為滑動*/
if(isMove && Math.abs(distanceX) > 50){
if(distanceX > 0){
rightCallback && rightCallback.call(this,e);
}else{
leftCallback && leftCallback.call(this,e);
}
}
/*重置參數*/
isMove = false;
startX = 0;
distanceX = 0;
});
}
bindSwipeEvent(document.querySelector('.box'),function (e) {
console.log(this);
console.log(e);
console.log('左滑手勢');
},function (e) {
console.log(this);
console.log(e);
console.log('右滑手勢');
});
}