2010-12-12 58 views
1

我使用以下代碼來查明查看者正在訪問的頁面的哪一部分(類似Google書籍,以查找正在查看的頁面):減少.resize和.scroll方法的調用次數

$("#main-content").scroll(function() { 
      Nx.curPage = (Math.round($(this).scrollTop()/620)+1); 
      window.location.hash = "#"+Nx.curPage; 
      Nx.select(undefined); 
     }); 

也在另一部分我使用$(window).resize(...)來適合我的內容在當前窗口大小,這是調用每一個調整大小。正如你可以想象的那樣,這會使頁面變慢,特別是在較老的硬件上。有什麼辦法可以實現什麼時候滾動或調整大小停止,然後開始做的東西,所以減少進程的數量?有點像$("#main-content").scrollStop ???

回答

6

你可以做兩件事。

1)設置超時,使大小調整/滾動經過一番空閒狀態情況:

var timeout; 
$("#main-content").scroll(function() { 
    clearTimeout(timeout); 
    timeout = setTimeout(function(){ 
     Nx.curPage = (Math.round($(this).scrollTop()/620)+1); 
     window.location.hash = "#"+Nx.curPage; 
     Nx.select(); // note: undefined is passed by default 
    }, 200); 
}); 

2)限制呼叫的次數/秒:

var lastScroll = 0; 
$("#main-content").scroll(function() { 
    var now = +new Date; 
    if (now - lastScroll > 100) { // only execute if (elapsed > 100ms) 
    Nx.curPage = (Math.round($(this).scrollTop()/620)+1); 
    window.location.hash = "#"+Nx.curPage; 
    Nx.select(); 
    lastScroll = now; 
    }   
}); 

+0

ms的數量當然只是例子。你可以和他們一起玩,以獲得最好的結果。 – galambalazs 2010-12-12 08:53:40

1

請嘗試下面的功能。它會檢查用戶是否滾動過某個特定的號碼。但是該功能僅在設置的時間間隔(下面示例中每秒鐘5次)觸發,而不是在滾動期間連續觸發。

var scrollCheck; 

    $(window).on('scroll', function() { 
     clearInterval(scrollCheck); 
     scrollCheck = setInterval(function(){ 
      clearInterval(scrollCheck); 
      scrollPosition = $(this).scrollTop(); 
          scrollAmount = 150 // no. of pixels that have been scrolled from top 

      if(scrollPosition > scrollAmount){ 
       alert('scrolled past point') 
      }else{ 
       alert('not scrolled past point') 
      } 

     },200); 
    });