提问者:小点点

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


我想要的是固定导航,与NEXT和PREV按钮基本上滚动页面到下一个div类“section”。

我将jQuery设置为在NEXT和PREV hrefs中添加一个click函数。这个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://jsfidle.net/adskh/1/

我有一个console.log正在检查(that.next())以确定下一个.节将是什么,但它给我返回了一些非常奇怪的结果。

为什么这不是预期的工作?


共1个答案

匿名用户

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

从jQuery文档中获取.next()

获取匹配元素集合中每个元素紧接其后的同级元素。

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