2013-02-28 53 views
7

我想要的是固定导航,使用NEXT和PREV按钮基本上将页面滚动到具有“section”类的下一个div。jQuery使用Next/Previous按钮滚动到下一个Div类

我已经设置jQuery实质上添加一个点击功能到NEXT和PREV hrefs。这个点击函数然后将使用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()});  
    } 
}); 

我目前工作的jsfiddle有大量注释jQuery来帮助你消化:http://jsfiddle.net/ADsKH/1/

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

为什么这不按预期工作?

回答

9

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

从jQuery文档.next()

获取匹配元素集合中每个元素的紧接着的同胞。

Here's a working example based on your code

+0

哗一下一个简单的解决方案!...这是字面上的货架我的大脑了几个小时。 感谢您的帮助! – richie 2013-02-28 03:56:01

+1

任何人都可以给我一个想法,为什么上面的代码不能在Firefox中工作? 我试过在文档中包装所有东西。准备就绪的功能,但它似乎并不奏效。 有没有什么固有的Firefox会阻止这种工作?任何帮助表示赞赏。 – richie 2013-05-31 23:20:34

+1

@richie,看[这个答案](http://stackoverflow.com/a/8149216)。 – pdoherty926 2013-06-01 04:41:52