これを試して:
var header_height = $('#nav').outerHeight();
var sections = [];
$('#nav a').each(function(){
var section = $(this.hash).offset()
sections.push({
'link':$(this).parent(),
'top' : $(this.hash).offset().top-header_height,
'bottom' : $(this.hash).offset().top + $(this.hash).outerHeight() -header_height
});
});
$('#nav a').click(function(e) {
e.preventDefault();
$('html,body').animate({
scrollTop: $(this.hash).offset().top - header_height
}, 500);
});
$(window).scroll(function(){
for(var i = 0; i < sections.length; i++)
if($(window).scrollTop() >= sections[i].top &&
$(window).scrollTop() <= sections[i].bottom){
sections[i].link.addClass('selected')
.siblings().removeClass('selected');
}
});
イベントをのリンクに直接添付しました#nav
。選択したクラスを親要素に追加し、親要素の兄弟から削除します。また、スクロールオフセットを70ピクセル少なくし、ナビゲーションの高さとパディングを減らします。
更新:特定のセクションのみのセクションへの参照はありません。これは、展開したり、新しいリンクやセクションを追加したりしても、JavaScriptを更新しなくても機能することを意味します。
フィドル:
http: //jsfiddle.net/iambriansreed/5Ta8j/