2013-02-28 73 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