Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Created April 13, 2014 07:20
Show Gist options
  • Save simplelife7/10572987 to your computer and use it in GitHub Desktop.
Save simplelife7/10572987 to your computer and use it in GitHub Desktop.
【JS】判断touch方向
/**
obj:触发元素;
dir:期望触发方向;'up','down','left','right'
fn :触发后的回调函数
*/
var touchEvent = function(obj,dir,fn){
this.pos = {x:0,y:0};//开始触发位置
var me = this;
obj.addEventListener('touchstart',function(event){
var touch = event.touches[0];
me.pos.x = touch.pageX;
me.pos.y = touch.pageY;
},false);
obj.addEventListener('touchmove',function(event){
var touch = event.touches[0];
me.curtouch = {
x:touch.pageX,
y:touch.pageY
}
},false);
obj.addEventListener('touchend',function(event){
if(me.checkDirV(me.pos,me.curtouch)==dir ||me.checkDirH(me.pos,me.curtouch)==dir){
(typeof fn=='function')&&fn();
}
},false);
}
touchEvent.prototype = {
posdiff:100,//触发敏感度
checkDirV:function(a,b){
return Math.abs(a.y-this.posdiff)>b.y?(a.y>b.y?'up':'down'):'';
},
checkDirH:function(a,b){
return Math.abs(a.x-this.posdiff)>b.x?(a.x>b.x?'left':'right'):'';
}
}
////eg:new touchEvent(document.getElementById('content'),'left',function(){alert(34);});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment