2010-10-08 39 views
3

我有一個具有固定浮動導航的單頁網站。我希望能夠通過向相關導航標籤添加一個「on」類來突出顯示用戶所在的部分。使用jQuery根據滾動位置更改一個類

當用戶不在該部分時需要刪除此類,並且新的當前部分需要反映在導航欄中。

這不能通過點擊功能來完成,因爲用戶仍然可以在頁面上下滾動。我知道如果這甚至可以完成或從哪裏開始,因爲我的jQuery非常有限。

任何幫助將非常感激。

這裏是我當前網頁,它不具有任何活躍導航高亮:http://ec2.dragonstaff.com/www.creativegems.co.uk/

+1

不要混淆你的網址,這不是慌張,讓你看起來像你試圖發送垃圾郵件。我在一個沙箱中打開了這個URL,以確保你沒有試圖欺騙別人(我很高興你沒有)。 – Incognito 2010-10-08 18:16:25

+1

我使用了我的編輯權限並且未對URL進行模糊處理。享受,user257493。 :) – aem 2010-10-08 19:29:51

回答

9

這似乎與您的網站的工作:

var $sections = $('section'); // all content sections 
var $navs = $('nav > ul > li'); // all nav sections 

var topsArray = $sections.map(function() { 
    return $(this).position().top - 300; // make array of the tops of content 
}).get();         // sections, with some padding to 
              // change the class a little sooner 
var len = topsArray.length; // quantity of total sections 
var currentIndex = 0;  // current section selected 

var getCurrent = function(top) { // take the current top position, and see which 
    for(var i = 0; i < len; i++) { // index should be displayed 
     if(top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1]) { 
      return i; 
     } 
    } 
}; 

    // on scroll, call the getCurrent() function above, and see if we are in the 
    // current displayed section. If not, add the "selected" class to the 
    // current nav, and remove it from the previous "selected" nav 
$(document).scroll(function(e) { 
    var scrollTop = $(this).scrollTop(); 
    var checkIndex = getCurrent(scrollTop); 
    if(checkIndex !== currentIndex) { 
     currentIndex = checkIndex; 
     $navs.eq(currentIndex).addClass("selected").siblings(".selected").removeClass("selected"); 
    } 
}); 
+0

這很好,謝謝帕特里克。 我必須做的唯一變化是在兄弟姐妹,因爲它需要知道它是一個類: 兄弟姐妹(「。selected」) – richardpixel 2010-10-10 12:43:21

+0

@Richardpixel - 啊是的,我錯過了''。固定。很高興你抓住了它,它爲你工作。 :o) – user113716 2010-10-10 15:15:36

+0

經過一些更多的測試,這在IE中看起來並不起作用(6,7,8或9)。不要以爲你有任何想法,爲什麼會發生這種情況? – richardpixel 2010-10-11 08:07:46

0

您可以用

var scrollTop=$(window).scrollTop(); 

http://api.jquery.com/scrollTop

然後抓住窗口的scrollTop的你通過內容<div> s並累積增加它們的高度,直到達到足夠接近scrollTop的值。關於如何處理重疊問題,您可能必須稍微嘗試一下。

一旦你發現你滾動到了你的投資組合的內容,你將相關的類添加到導航元素。

0

這裏只是將這個作爲一種替代方案:

有一個叫Waypoints一個jQuery插件。實現非常簡單。在他們的網站上的例子是:

$('.thing').waypoint(function(direction) { 
    alert('Top of thing hit top of viewport.'); 
}); 

所以,只要你知道什麼元素被調用,Waypoint將是愚蠢的簡單實現。