highlight navigation dots while scrolling down on page

后端 未结 1 606
执念已碎
执念已碎 2020-12-22 07:01

Will try to explain this :) I have a navigation that scrolls to different anchors on the page. When the user is on one of the anchors the navigation shows an active link.

相关标签:
1条回答
  • 2020-12-22 07:30

    EDIT : Modified the code for better performance.

    I made a JSFiddle that work here what I added

    var parPosition = [];
            $('.par').each(function() {
                parPosition.push($(this).offset().top);
            });
    
            $(document).on('scroll', function() {
                var position = $(document).scrollTop(),
                    index;
    
                for (var i=0; i<parPosition.length; i++) {
                    if (position <= parPosition[i]) {
                        index = i;
                        break;
                    }
                }
    
                $('.navigation ul li a')
                   .removeClass('active')
                   .eq(index)
                   .addClass('active');
            });
    

    As you can see, I added the class "par" to all paragraph. JSFiddle

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