当页面滚动到达特定ID时添加类 [英] Add class when page scroll reach at specific id

查看:101
本文介绍了当页面滚动到达特定ID时添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div <div id="Section1"> abc </div>中有一个ID,并链接了<a id="link" href="#Section1">Section1</a>

I have an Id in a div <div id="Section1"> abc </div> and link <a id="link" href="#Section1">Section1</a>

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

Question: When I scroll page and page reach at id #Section1 a class should be add in the link, link should like<a id="link" href="#Section1" class="ok">Section1</a>

推荐答案

您可以这样使用:

$(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

请参阅 toggleClass 的文档.

这篇关于当页面滚动到达特定ID时添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆