admin管理员组

文章数量:1579086

网上分享的阻止事件 会阻止上下左右所有滚动 下面写的只会阻止左右 不会阻止上下 并且可以知道滑动了多少可以打印distanceX看看滚动值

写了个小例子 左右滑动超过100px 则执行一件事

var startPos = 0,endPos = 0,isScrolling = 0;

document.addEventListener('touchstart',function(event){

startX = event.changedTouches[0].pageX,

startY = event.changedTouches[0].pageY;

var touch = event.targetTouches[0]; //touches数组对象获得屏幕上所有的touch,取第一个touch

startPos = {x:touch.pageX,y:touch.pageY,time:+new Date}; //取第一个touch的坐标值

isScrolling = 0; //这个参数判断是垂直滚动还是水平滚动

}, false);

//解绑事件 web前端开发

document.addEventListener('touchend',function(event){

document.removeEventListener('touchmove',this,false);

document.removeEventListener('touchend',this,false);

}, false);

document.addEventListener('touchmove',function(event){

endX = event.changedTouches[0].pageX,

endY = event.changedTouches[0].pageY;

distanceX = endX-startX;

distanceY = endY-startY;

//当屏幕有多个touch或者页面被缩放过,就不执行move操作

if(event.targetTouches.length > 1 || event.scale && event.scale !== 1) return;

var touch = event.targetTouches[0];

endPos = {x:touch.pageX - startPos.x,y:touch.pageY - startPos.y};

isScrolling = Math.abs(endPos.x) 

if(isScrolling === 0){

if(Math.abs(distanceX)>Math.abs(distanceY) && distanceX>0){

if (distanceX > 100) {

alert('yes')

}

}else if(Math.abs(distanceX)>Math.abs(distanceY) && distanceX<0){

if (distanceX 

alert('yes1')

}

}

event.preventDefault(); //阻止触摸事件的默认行为,即阻止滚屏

}

}, false);

本文标签: 浏览器事件历史手机js