使用jQuery更改依赖于滚动位置的类

我有一个单页网站,它有一个固定的浮动导航。 我希望能够通过在相关导航标签上添加“on”类来突出显示用户所在的部分。

当用户不再使用该部分时,需要删除此类,然后需要在导航中反映新的当前部分。

这不能通过点击function完成,因为用户仍然可以只在页面上下滚动。 我知道是否可以这样做或者从哪里开始,因为我的jQuery非常有限。

任何帮助将非常感激。

这是我当前的网页,没有任何主动导航突出显示: http : //ec2.dragonstaff.com/www.creativegems.co.uk/

这似乎适用于您的网站:

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"); } }); 

你可以抓住窗口的scrollTop

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

http://api.jquery.com/scrollTop

然后你浏览内容

并累积它们的高度,直到你得到一个足够接近scrollTop的值。 您可能需要对如何处理重叠进行一些实验。

一旦您确定滚动到您的投资组合的内容,就会将相关类添加到nav元素。

只需在此处添加此选项:

有一个名为Waypoints的jQuery插件。 实施非常简单。 他们网站上的示例是:

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

因此,只要您知道调用该元素的内容,Waypoints将很容易实现。