1.判断滑动的手势条件

  • 触发touchmove事件
  • 移动的超过一定的距离,如10px, 像滑动了1px,2px这类的距离太小,不能视为滑动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background-color: hotpink;
}
</style>
</head>
<body>
<div class="box">

</div>
</body>

<script>

window.onload = function(){
var bindSwiperEvent = function(dom, leftCallBack, rightCallback){
// 判断手势的条件
// 必须滑动 滑动距离超过10px
var isMove = false;
var startX = 0;
var distanceX = 0;

dom.addEventListener( 'touchstart', function(e){
startX = e.touchs[0].clientX;
})

dom.addEventListener('touchmove', function(e){
isMove = true;
var moveX = e.touchs[0].clientX;
distanceX = moveX - startX;
})

dom.addEventListener('touchend',function(e){
if(isMove && Math.abs(distanceX >= 10)){
// 右滑动
if(distanceX>0){
rightCallback && rightCallback.call(this,e);
}
// 左滑动
else{
leftCallBack && leftCallBack.call(this,e);
}
}
// 重置参数
isMove = false;
startX = 0;
distanceX = 0;
})
}

bindSwiperEvent( document.querySelector('.box'), function(e){
console.log('左滑动')
}, function(e){
console.log('右滑动')
} )
}
</script>

</html>