Add class to anchor link when scrolling past ancho

2019-01-27 05:53发布

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 the link is clicked and also when the window/page scrolls to appropriate div using jQuery?

For example, there are 3 anchor links which link to the 3 sections:

<ul>
  <li><a href="#section1">Section 1</li>
  <li><a href="#section2">Section 2</li>
  <li><a href="#section3">Section 3</li>
</ul>

Then there are the 3 sections:

<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>

What I would like to accomplish is when the page scrolls to one of the divs or an anchor is clicked the class of the anchor link would toggle. So if the #section 1 anchor is clicked or the page scrolls to the #section1 div, a class would be added to the section1 anchor link. If section 2, then #section2 link would receive the class and section1 link would have the class removed and so on.

I think I may need a way to track the positioning of each section div and to then toggle the class on the appropriate link, but I am not too sure where to begin.

Thanks in advance for any help or advice.

标签: jquery scroll
1条回答
神经病院院长
2楼-- · 2019-01-27 06:28

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.

查看更多
登录 后发表回答