使用jQuery根据滚动位置更改类

使用jQuery根据滚动位置更改类,jquery,scroll,Jquery,Scroll,我有一个单页网站,有固定浮动导航。我想通过向相关导航标签添加一个say“on”类来突出显示用户所在的部分 当用户不再在该部分时,需要删除该类,并且新的当前部分需要反映在nav中 这不能通过点击功能来完成,因为用户仍然可以上下滚动页面。我知道这是否可以实现,或者从哪里开始,因为我的jQuery非常有限 任何帮助都将不胜感激 这是我当前的网页,没有任何活动导航突出显示:你可以用 var scrollTop=$(window).scrollTop(); 然后浏览内容s,将它们的高度累加起来,直到得

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

当用户不再在该部分时,需要删除该类,并且新的当前部分需要反映在nav中

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

任何帮助都将不胜感激


这是我当前的网页,没有任何活动导航突出显示:

你可以用

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

然后浏览内容
s,将它们的高度累加起来,直到得到一个足够接近scrollTop的值。关于如何处理重叠,您可能需要进行一些试验


一旦你计算出你的文件被滚动到(比如)你的公文包的内容,你就将相关的类添加到nav元素中。

这似乎适用于你的网站:

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");
    }
});
var$sections=$('section');//所有内容部分
var$navs=$('nav>ul>li');//所有导航部分
var topsArray=$sections.map(函数(){
return$(this).position().top-300;//生成内容顶部的数组
}).get();//节,并添加一些填充
//早点换个班
var len=topsArray.length;//总截面数量
var currentIndex=0;//选定的当前节
var getCurrent=function(top){//获取当前的top位置,然后查看
对于(var i=0;itopsArray[i]&&topsArray[i+1]&&top
只需在此处添加以下内容作为替代:

有一个jQuery插件叫做。实现起来相当容易。他们网站上的例子是:

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

因此,只要您知道元素的名称,航路点就很容易实现

不要混淆你的URL,这不是twitter,让你看起来像是在发垃圾邮件。我在一个沙箱中打开了这个URL,只是为了确保你不是一个试图欺骗别人的混蛋(我很高兴你不是)。我使用了我的编辑能力,并消除了URL的模糊。享受,用户257493.:)谢谢你,帕特里克。我唯一需要做的改变是在兄弟姐妹中,因为它需要知道它是一个类:兄弟姐妹(“.selected”)@Richardpixel-啊,是的,我错过了
。固定的。很高兴你抓住了它,它对你有用o) 经过更多的测试,这在IE(6、7、8或9)中实际上似乎不起作用。“难道你不知道为什么会发生这种情况吗?”@richardpixel-取决于什么不起作用。
.scroll()
处理程序是否会启动?如果你不确定的话。在处理程序的顶部放置警报。如果您发现它没有启动,请尝试
$('body')。滚动(func…
而不是
$(文档)。滚动(func…
。感谢您的帮助,您的位置正确,但我需要$(窗口)。滚动(func…)。。。。