jQuery滚动,在页面滚动时(相对于部分)更改导航活动类 [英] jquery scroll, change navigation active class as the page is scrolling, relative to sections

查看:92
本文介绍了jQuery滚动,在页面滚动时(相对于部分)更改导航活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/motocomdigital/gUWdJ/


我正在追求一种jQuery滚动技术,我想适应我的项目.

I'm after a jquery scroll technique please that I would like to adapt to my project.

请在此处查看我的项目示例作为小提琴 http://jsfiddle.net/motocomdigital/gUWdJ/

Please see my project example as a fiddle here http://jsfiddle.net/motocomdigital/gUWdJ/

当前,您可以看到我的导航链接自动使相对于<section>的滚动动画.

Currently you can see that my nav links automatically animates the scrolling relative to the <section>'s.

我的问题是,使用$(window).scroll方法,当各节到达窗口顶部时,如何向nav a中添加.active类?

My question is, using the $(window).scroll method, how can I add a .active class to my nav a when the sections reach the top of the window?

例如,如果用户向下滚动页面(而不是导航链接),我希望向活动类添加相对的导航链接.指示您在页面上的位置.

So for example if the user scrolls down the page (instead of the navigation links), I want the active class to be added relative navigation link. Indicating where you are on the page.

当用户向下滚动页面时,每次我猜测时,都必须删除活动类,然后添加该活动类.

此外,您还必须考虑固定导航栏(偏移顶部窗口)的28px高度.

Also you will have to account for the 28px height of the fixed navigation bar, offset top window.


任何人都可以向我展示一种我可以尝试使用或适应的技术,或者可以使用jsfiddle来展示我:)

Can anyone please show me a technique that I can try and use or adapt, or perhaps show me using my jsfiddle :)


任何帮助将不胜感激,在此先感谢您!

Any help would be much appreciated, thanks in advance!


http://jsfiddle.net/motocomdigital/gUWdJ/


推荐答案

如果您希望使用更通用的功能:

If you wish a more generic function:

查看演示

$(window).scroll(function() {
    var windscroll = $(window).scrollTop();
    if (windscroll >= 100) {
        $('nav').addClass('fixed');
        $('.wrapper section').each(function(i) {
            if ($(this).position().top <= windscroll - 100) {
                $('nav a.active').removeClass('active');
                $('nav a').eq(i).addClass('active');
            }
        });

    } else {

        $('nav').removeClass('fixed');
        $('nav a.active').removeClass('active');
        $('nav a:first').addClass('active');
    }

}).scroll();​

这篇关于jQuery滚动,在页面滚动时(相对于部分)更改导航活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆