Add class to anchor link when scrolling past anchor div - jquery

前端 未结 1 1180
清歌不尽
清歌不尽 2020-12-20 07:40

I have a page that has anchors which link to appropriate sections of a page. I am wondering if anyone has any advice on how I may toggle the class of the anchor link when th

相关标签:
1条回答
  • 2020-12-20 08:01

    I would suggest finding the total height of each section. I am assuming there are no breaks in between each section as well. Then use jQuery to determine the window position. When the window position hits a certain value, make the class switch. Hopefully this can be done only with scrolling, so when you click on a link, it will scroll and the previously described function can run and change the classes for you.

    Here is some pseudo-code

    $(document).ready(function(){
        var section1Height = $('#section1').height();
        var section2Height = $('#section2').height();
        var section3Height = $('#section3').height();
    
        $(window).scroll(function() {
            var winTop = $(window).scrollTop();
            if(winTop >= section1Height && winTop <= section2Height){
                $('#section1').addClass("newClass").not().removeClass("newClass");
            } else if(winTop >= section2Height && winTop <= section3Height){
                $('#section2').addClass("newClass").not().removeClass("newClass");
            } else if(winTop >= section3Height){
                $('#section3').addClass("newClass").not().removeClass("newClass");
            }
        });
    });
    

    Again, this is just a quick example. With more details on your part, I can give a more detailed answer.

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