2012-11-23 86 views
1

我已經通過類似的問題進行了搜索,並覺得我已經嘗試了幾乎所有的東西都無濟於事。導航鏈接上的jQuery活動類不會改變

當用戶滾動到我的單頁網站的相應部分時,我想要一個類「.active」附加到頁面導航中的鏈接。當用戶繼續滾動時,該活動類將從鏈接中消失並被添加到下一個鏈接。

滾動的jQuery確實在代碼中工作,但似乎沒有其他。

這裏是我的地盤:http://tendigi.com/staging/

這裏是(縮短)的代碼段:

HTML:

<ul id="nav"> 
    <li><a href="#about">ABOUT</a></li> 
    <li><a href="#team">TEAM</a></li> 
    <li><a href="#portfolio">PORTFOLIO</a></li> 
    <li><a href="#process">PROCESS</a></li> 
    <li><a href="#brands">BRANDS</a></li> 
    <li><a href="#press">PRESS</a></li> 
    <li><a href="#blog">BLOG</a></li> 
    <li><a href="#meetup">MEETUP</a></li> 
    <li><a href="#contact">CONTACT</a></li> 
</ul> 

<section> 
    <a id="about">Header</a> 
Some Text 
</section> 
<section> 
    <a id="team">Header</a> 
Some Text 
</section> 
<section> 
    <a id="portfolio">Header</a> 
Some Text 
</section> 

的jQuery:

// Cache selectors 
var lastId, 
topMenu = $("#nav"), 
topMenuHeight = topMenu.outerHeight()+75, 
// All list items 
menuItems = topMenu.find("a"), 
// Anchors corresponding to menu items 
scrollItems = menuItems.map(function(){ 
    var item = $($(this).attr("href")); 
    if (item.length) { return item; } 
}), 
noScrollAction = false; 

// Bind click handler to menu items 
// so we can get a fancy scroll animation 
menuItems.click(function(e){ 
var href = $(this).attr("href"), 
    offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1; 
noScrollAction = true; 
$('html, body').stop().animate({ 
    scrollTop: offsetTop 
},{ 
    duration: 300, 
    complete: function() { 
     menuItems 
      .parent().removeClass("active") 
      .end().filter("[href=" + href +"]").parent().addClass("active"); 
     setTimeout(function(){ noScrollAction = false; }, 10); 
    } 
}); 
e.preventDefault(); 
}); 

// Bind to scroll 
$(window).scroll(function(){ 
if(!noScrollAction){ 
    // Get container scroll position 
    var fromTop = $(this).scrollTop()+topMenuHeight; 

    // Get id of current scroll item 
    var cur = scrollItems.map(function(){ 
    if ($(this).offset().top < fromTop) 
     return this; 
    }); 
    // Get the id of the current element 
    cur = cur[cur.length-1]; 
    var id = cur && cur.length ? cur[0].id : ""; 

    if (lastId !== id) { 
     lastId = id; 
     // Set/remove active class 
     menuItems 
     .parent().removeClass("active") 
     .end().filter("[href=#"+id+"]").parent().addClass("active"); 
    } 
    }  
});​ 

這是我的第一個問題在stackoverflow,所以我很抱歉,如果我沒有做到這一點正確!所以幫助會很高興。

謝謝!

回答

0

從我可以看到這是工作。雖然活動鏈接正在應用於<li />。如果你需要它的<a />改變這樣的:

.end().filter("[href=" + href +"]").parent().addClass("active"); 

到:

.end().filter("[href=" + href +"]").addClass("active"); 

希望幫助!

編輯

哎呦!你以前也需要更改這一行。因此,它是:

.parent().removeClass("active") 
.end().filter("[href=" + href +"]").parent().addClass("active"); 

到:

.removeClass("active") 
.filter("[href=" + href +"]").addClass("active"); 

你也像你需要5或6個像素來調整您的門檻......

+0

美妙,成功了!萬分感謝 :) – mkdesign

相關問題