首页 文章

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

提问于
浏览
7

我想要的是固定导航,使用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()});     
  }
});

我目前正在使用具有大量评论jQuery的JSfiddle来帮助您消化:http://jsfiddle.net/ADsKH/1/

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

为什么这不按预期工作?

1 回答

  • 9

    你的 that 找不到 .next('.section') ,因为它嵌套在 .navigation 中 .

    来自 .next() 的jQuery文档 .

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

    Here's a working example based on your code

相关问题