首页 > 代码库 > 手机的touch事件(基于jquery)

手机的touch事件(基于jquery)

javascript代码:

$.swipe=function(opt){
  var o = $.extend({
    mainSelector:"",
    swipeLeft:function(e,v){},
    swipeRight:function(e,v){},
    swipeEnds:function(v,e){}
}, opt || {});
  var startX=0,startY=0;
var obj={
    touchStart: function (e){
        var touchx= e.touches[0].pageX;
        var touchy= e.touches[0].pageY;
        startX = parseInt(touchx,10);
        startY = parseInt(touchy,10);
    },
    touchMove:function(e){
        var touchmx= e.touches[0].pageX,
        touchmy= e.touches[0].pageY,
        dirX=parseInt(touchmx-startX,10);
        dirY=parseInt(touchmy-startY,10);
        if(dirX<0){
            o.swipeLeft(e,dirX);
        }else{
           o.swipeRight(e,dirX);
        }
        
        if(dirY<0){
            o.swipeTop(e,dirY);
        }else{
            o.swipeBottom(e,dirY);
        }
    },
    touchEnd:function(e){
       o.swipeEnds(e);
    },
    bindEvent:function(els){
        var elem=$(els);
        for(var i=0,_len=elem.length;i<_len;i++){
          elem[i].addEventListener(‘touchstart‘, obj.touchStart, false);
          elem[i].addEventListener(‘touchmove‘, obj.touchMove, false);
          elem[i].addEventListener(‘touchend‘, obj.touchEnd, false);
        }
    }
};
obj.bindEvent(o.mainSelector);
return obj;
}; 

 

传入的是选择器和swipeLeft,swipeRight的回调事件