2012-08-28 52 views
3

我使用jQuery和touchSwipe插件向上和向下滚动内容。我有一些数学相关的问题,想看看社区是否能够迅速帮助我弄清楚这一点。jQuery touchSwipe内容滚动功能

touchSwipe“distance”变量只返回从零开始的正值,所以当用户向上滑动然后决定向下滑动时会出现问题,因为距离值从ex改变:(0 initial,15up, 32up,20up,5up,10down,40down)。我创建了4条if语句来捕捉所有这些情况。如果陈述如何处理“方向改变”?

touchSwipe:http://labs.skinkers.com/touchSwipe/

的向上和向下滑动功能:

var _scrolling=false; 
var _prev=0; 
$("#list").swipe({ 
    swipeStatus:function(event, phase, direction, distance, fingerCount) { 
    if(phase=="end"){return false;} 
    if(phase=="move" && !_scrolling) { 
     var t = parseInt($("#list").css("top").split('px')[0]); 
     var s = 0; 
     if(direction=="up" && (distance-_prev) > 0){ 
     //still moving up 
     s = t-(distance-_prev); 
     _prev=distance; 
     } else if(direction=="up" && (distance-_prev) < 0){ 
      //direction change - moving down  
     } else if(direction=="down" && (distance-_prev) > 0){ 
     //still moving down 
      s = t+(distance-_prev); 
     _prev=distance; 
     } else if(direction=="down" && (distance-_prev) < 0){ 
      //direction change - moving up 
     } 
     _scrolling=true; 
     $("#list").animate({ top:s }, 70, function() {_scrolling=false;}); 
    }<!--if end--> 
    }<!--swipeStatus end--> 
}); 

回答

1

所以几天后我就能够解决这一问题,修订原有的“swipeStatus”功能,并创建一个漂亮高效的全功能函数来使用touchSwipe jQuery插件滚动绝对区域。

解决方案:

function swipeScroll(c,b,pd,f){ 
    $(c).swipe({//c style must be position:absolute;top:0; b style must be position:relative; 
     swipeStatus:function(event, phase, direction, distance, fingerCount) { 
     if(phase=="start"){pd=0;} 
     if(phase=="end"){return false;} 
     if(phase=="move" && pd!=distance){ 
      var t = parseInt($(c).css("top"),10); 
      var u = (pd-distance); 
      if(direction=="up" && t != u){ t+=u; }else if(direction=="down" && t != -u){ t-=u; } 
      pd=distance; 
      if(t > 0 || $(b).height() > $(c).height()){t=0;}//top of content 
      else if(($(b).height()-t) >= $(c).height()){//bottom of content 
      t=$(b).height()-$(c).height(); 
      if(typeof f != "undefined"){f();} 
      } 
      $(c).css("top",t); 
     } 
     } 
    }); 
} 

功能参数解释:

C:要滚动 B中的绝对含量:围绕含量 “C” PD相对容器:变量来存储从前一次滚动移动的距离 f:滚动到达底部时调用的函数

注: “b” 的必须有一个相对位置和 “c” 的一个绝对位置与顶部:0

实例:

var distance; 
swipeScroll("#list","#body",distance, function() { alert("bottom"); }); 

研究:

代替使用“$(c)中的CSS(” 顶部 “T);”我也使用jQuery animate()函数测试了这个效果,以实现平滑的滑动效果,但这实际上导致了滚动缓慢。一个动画给出了意想不到的结果,因为“t”有时会在快速滑动时跳过“0”,并且方向会从“上”变为“下”,导致滚动的内容突然跳跃。

0

刚一说明:使用线路

if (phase == "end") { return false; } 

将防止使用窃听事件。所以如果你需要这个事件,你必须删除这一行。