2015-02-06 238 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