使用jQuery滚动到下一个div类并配合上一个/下一个按钮

7
我希望固定的导航栏上有“下一个”和“上一个”按钮,可以滚动页面到下一个class为"section"的div。
我已经设置了jQuery以添加单击功能到NEXT和PREV hrefs。这个单击函数将使用ScrollTop来移动到下一个class为.section的div。
以下是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内。

来自jQuery .next()文档。

获取匹配元素集合中每个元素紧邻的后续同胞元素。

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


哇,多么简单的解决方案!这个问题实际上让我苦恼了几个小时。感谢您的帮助! - richie
1
有没有人能给我一个想法,为什么上面的代码在Firefox中不能工作?我尝试将所有内容都包装在doc. ready函数中,但似乎并不起作用。是否有任何固有的Firefox属性会阻止它正常工作?感谢任何帮助。 - richie
再次感谢您的帮助!如果有人需要另一种方法,这里提供了一个示例,它可以移动动画并在Firefox中工作,而无需添加/编辑溢出。 - richie
1
@pdoherty926,你知道如何扩展这个功能,使得手动上下滚动页面时下一页/上一页的按钮不会混乱吗?所谓的混乱是指更糟糕的用户体验,因为当手动滚动发生时,滚动条会跳回到之前的位置,然后从那个点开始滚动。如果能够无缝地从当前页面位置中了解全页和下一页/上一页,将会更好。 - AdamJones
有没有办法将导航文本(下一个/上一个)转换为图像?或者通过类(例如:.prevButton.nextButton)触发下一个/上一个按钮,这样我们就可以将其替换为图像而不是文本? - Chun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接