jQuery使用下一个/上一个按钮滚动到下一个Div类

ric*_*hie 7 javascript jquery frontend scroll

我想要的是固定导航,使用NEXT和PREV按钮基本上将页面滚动到下一个具有"section"类的div.

我已经设置了jQuery,实际上是为NEXT和PREV hrefs添加了一个click函数.然后,此单击函数将使用ScrollTop移动到具有.section类的下一个duv.

这是jQuery:

$('div.section').first();
// binds a click event-handler to a elements whose class='display'
$('a.display').on('click', function(e) {
    // prevents the default action of the link
    e.preventDefault();
    // assigns the text of the clicked-link to a variable for comparison purposes
    var t = $(this).text(),
      that = $(this);
      console.log(that.next())    
      // checks if it was the 'next' link, and ensures there's a div to show after the currently-shown one
      if (t === 'next' && that.next('div.section').length > 0) {
      //Scroll Function
      $('html, body').animate({scrollTop:that.next('div.section').scrollTop()});
  } 
    // exactly the same as above, but checking that it's the 'prev' link
    else if (t === 'prev' && that.prev('div.section').length > 0) {
      //Scroll Function
       $('html, body').animate({scrollTop:that.prev('div.section').scrollTop()});     
  }
});
Run Code Online (Sandbox Code Playgroud)

我目前正在研究JSfiddle,其中包含大量评论的jQuery,以帮助您消化:http://jsfiddle.net/ADsKH/1/

我有一个console.log当前检查(that.next())以确定下一个.section将是什么,但它给了我一些非常奇怪的结果.

为什么这不按预期工作?

pdo*_*926 9

that找不到一个,.next('.section')因为它嵌套在里面.navigation.

来自jQuery文档.next().

获取匹配元素集中每个元素的紧随其后的兄弟.

这是一个基于您的代码的工作示例