Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

jsfiddle - jquery scroll, change navigation active class as the page is scrolling, relative to sections

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


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

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

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

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.

The active class will have to be removed then added every time I'm guessing as the user scrolls down the page.

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


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/


enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you wish a more generic function:

SEE DEMO

$(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();?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...