2012-08-28 53 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; } 

將防止使用竊聽事件。所以如果你需要這個事件,你必須刪除這一行。