2015-02-06 256 views
0

我有一個很長的頁面分解成<section>標籤。有固定的位置導航可以在頁面上下滾動。我需要每次按下「向下」按鈕將下一個<section>滾動到頁面頂部。 「向上」按鈕也一樣,它應該滾動之前的<section>到頁面的頂部。我不希望在指定的scrollTo函數的每個部分中包含導航實例。我寧願它更普遍。如果每個部分都有鏈接,那將很簡單。但是,導航是位置:固定的,所以我不能使用.next()或.closest()。我想我必須索引部分的數量並逐步通過它們?滾動到每個部分的頂部點擊

這僅適用於第一次按下:

$('#scrollWindowUp').click(function(e){ 
    e.preventDefault(); 
    $('html, body').animate({ scrollTop: ($('section').next().offset().top)},500); 
}); 

$('#scrollWindowDown').click(function(e){ 
    e.preventDefault(); 
    $('html, body').animate({ scrollTop:($('section').prev().offset().top)},500); 
}); 

這裏是一個fiddle

每個部分是視口的高度,所以你只看到一次一個。我只是抓住$('window').height();並將其應用到<section>,以便填滿窗口。我嘗試過使用該計算來進行滾動,但它總是關閉一點。

回答

1

存儲當前指數或元素可以有,如果用戶滾動不期望的作用頁面本身,因爲它會跳到下一個部分,當他們在#scrollWindowDown最後點擊,而不是屏幕上的下一節。

要允許按鈕從當前部分滾動而不管用戶是否滾動,您需要計算哪一部分當前可見。

function getCurrentSection() { 
    var cutoff = $(window).scrollTop(); 
    var curIndex = 0; 
    for(var index = 0; index < $('section').length; index++){ 
     if ($('section').eq(index).offset().top >= cutoff) { 
      curIndex = index; 
      break; 
     } 
    } 
    return curIndex; 
}; 

$('#scrollWindowUp').click(function(e){ 
    e.preventDefault(); 
    var curIndex = getCurrentSection(); 
    if (curIndex === 0) { return; } 
    $('html, body').animate({ scrollTop: ($('section').eq(curIndex-1).offset().top - 1)},500); 
}); 

$('#scrollWindowDown').click(function(e){ 
    e.preventDefault(); 
    var curIndex = getCurrentSection(); 
    if (curIndex === $('section').length) { return; } 
    var cutoff = $(window).scrollTop(); 
    if ($('section').eq(curIndex).offset().top !== cutoff+1) { curIndex = curIndex-1; } /* Check if the current section is at the top of the page or has been scrolled */ 

    $('html, body').animate({ scrollTop: ($('section').eq(curIndex+1).offset().top - 1)},500); 
}); 
+0

非常好,它確實解決了您提出的問題。我會試着去嘗試並更好地理解它在做什麼。偉大的工作,真的很感激它。 – 2015-02-06 16:20:09

1

你需要設置一個全局變量來記住你所在的元素。每次你去$('section'),它都會抓住列表中的第一個元素。

var $section = $('section').first(); 

$('#scrollWindowUp').click(function(e){ 
    e.preventDefault(); 

    if ($section.is('section:last')) { 
     return; 
    } 

    $section = $section.next(); 

    scroll(); 
}); 

$('#scrollWindowDown').click(function(e){ 
    e.preventDefault(); 

    if ($section.is('section:first')) { 
     return; 
    } 

    $section = $section.prev(); 

    scroll(); 
}); 

function scroll() { 
    $('html, body').animate({ scrollTop: ($section.offset().top)},500);  
} 
+0

該死的男人,太棒了。謝謝你,先生。 – 2015-02-06 04:23:34