Use jQuery to change a class dependent on scroll position

后端 未结 3 1582
失恋的感觉
失恋的感觉 2021-01-01 06:44

I have a single page website which has a fixed floating nav. I want to be able to highlight which section the user is on by adding a class of say \"on\" to the relevant navi

相关标签:
3条回答
  • 2021-01-01 07:06

    This seems to work with your site:

    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");
        }
    });
    
    0 讨论(0)
  • 2021-01-01 07:06

    You could grab the window's scrollTop with

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

    http://api.jquery.com/scrollTop

    Then you go through the content <div>s and cumulatively add their height up until you get to a value that is close enough to scrollTop. You probably have to experiment a little with regards to how you handle overlap.

    Once you figured that your are scrolled to the content of, say, your portfolio you add the relevant class to the nav element.

    0 讨论(0)
  • 2021-01-01 07:23

    Just adding this here as an alternative:

    There is a jQuery plugin called Waypoints. Implementation is pretty easy. The example on their site is:

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

    So, as long as you know what the element is called, Waypoints will be stupid simple to implement.

    0 讨论(0)
提交回复
热议问题