当页面滚动到达特定ID时添加类

Muh*_*iaz 6 jquery

我在div <div id="Section1"> abc </div>和链接中有一个Id<a id="link" href="#Section1">Section1</a>

问题:当我滚动页面和页面到达id时,#Section1应该在链接中添加一个类,链接应该是<a id="link" href="#Section1" class="ok">Section1</a>

Bho*_*yar 5

你可以像这样使用:

$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    $('#link').toggleClass('ok',
     //add 'ok' class when div position match or exceeds else remove the 'ok' class.
      scroll >= $('#Section1').offset().top
    );
});
//trigger the scroll
$(window).scroll();//ensure if you're in current position when page is refreshed
Run Code Online (Sandbox Code Playgroud)

请参阅toggleClass的文档.