单页网站上的复杂活动状态导航

HTML:

JS:

 $('nav li a').click(function(e) { e.preventDefault(); $('a').removeClass('active-state-navigation'); $(this).addClass('active-state-navigation'); $('logo-ribbon a').click(function(){ $('nav li').removeClass('active-state-navigation'); }); }); 

我需要实现的目标如下:

  • 一旦你点击一个菜单项,一个经典的活动状态..这个我已经用js的第一行实现了

  • 我希望在页面滚动时也能触发活动状态。 所以,如果我滚动,让我们说,#contact部分,活动状态更改为“联系人”菜单项

  • 我还需要这个,如果我点击“.logo-ribbon a”,“活动状态导航”将被移除到导航中的任何位置。

你的意思是卷轴? 点击这里http://jsfiddle.net/mekwall/up4nu/

 // Cache selectors var lastId, topMenu = $("#top-menu"), topMenuHeight = topMenu.outerHeight()+15, // 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; } }); // 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; $('html, body').stop().animate({ scrollTop: offsetTop }, 300); e.preventDefault(); }); // Bind to scroll $(window).scroll(function(){ // 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"); } });