2015-11-06 210 views
1

我的網頁上有2個div。第一個div是「#pattern」(紅色),第二個是「#projets」(藍色)滾動時滾動到div,當div消失時滾動到頂部

第一次使用滾動時,窗口自動滾動到第二個div「#projets」 。我正在使用jquery滾動到插件。 它工作得很好,即使用戶滾動滾動大量的滾動時,可能會偏離「#projets」div ...如果有人有一個想法來糾正這將是很好,但這不是我的主要麻煩...

現在我想滾動回頁面的頂部(「#pattern」div),只要「#pattern」div再次出現滾動時,紅色的一個。所以基本上它應該是儘快從我的div「#projets」屏幕的頂部偏移是supperior爲1.

我已經嘗試過很多解決方案沒有結果,使用標誌,多個條件...它可以是相同種類的這個頁面上的事情,但用戶應該abble頁面內自由滾動,沒有滾動的哈希散列:

http://www.thepetedesign.com/demos/onepage_scroll_demo.html

這裏是我的html:

<div id="pattern"></div> 
<div id="projets"></div> 
我的css:
#pattern { 
    height:300px; 
    width: 100%; 
    background-color:red 
} 

#projets { 
    height:800px; 
    width: 100%; 
    background-color:blue 
} 

和我的jQuery:

var flag=0 ; 

$(window).on('scroll',function(){ 

var top_projets_position = $("#projets").offset().top - $(window).scrollTop(); 

    if((flag==0) && $(window).scrollTop()>1){ 
     $(window).scrollTo('#projets', 500); 
     flag=1; 
    }  

     if($(window).scrollTop()==0){ 
     flag=0; 
    } 

}); 

這裏的jsfiddle:

http://jsfiddle.net/jdf9q0sv/

希望有人能幫助我,我不能找出我在做什麼錯,也許是一種錯誤的方法!感謝

回答

1

看起來你需要跟蹤的三件事:

  1. 滾動方向發生。
  2. 您目前正在查看的區域。
  3. 如果滾動動畫正在發生(我們需要等待,直到完成,否則會出現問題)。

http://jsfiddle.net/vx69t5Lt/

var prev_scroll = 0;   // <-- to determine direction of scrolling 
var current_view ="#pattern"; // <-- to determine what element we are viewing 
var allowed = true;   // <-- to prevent scrolling confusion during animation 

var top_projets_position = $("#projets").offset().top + 1; 

$(window).on('scroll',function(){ 
    var current_scroll = $(window).scrollTop(); 

    if(current_scroll < top_projets_position && current_view=="#projets" && current_scroll < prev_scroll){ 
     scrollToTarget("#pattern"); 
    } 
    if($(window).height() + current_scroll > top_projets_position && current_view=="#pattern" && current_scroll > prev_scroll){ 
     scrollToTarget("#projets"); 
    } 

    prev_scroll = current_scroll; 
}); 

function scrollToTarget(selector){ 
    if(allowed){ 
     allowed = false; 
     $(window).scrollTo(selector, { 
      'duration':500, 
      'onAfter': function(){ allowed = true; current_view = selector;} 
     }); 
    } 
} 

這是基於你的原始代碼只是一個快速的解決方案。更好的解決方案是做更多的面向對象(OOP)和追蹤對象中的值。也許在創建對象時需要一些元素,獲取所有邊界並在滾動處理程序中使用邊界來確定何時滾動到下一個div。