Add class to body for each scrolling based on section ID

旧巷老猫 提交于 2020-07-20 04:42:23

问题


I have a page layout like this.

<body>
  <section id="s1">...</div>
  <section id="s2">...</div>
  <section id="s3">...</div>
</body>

I need to add class to body tag whenever the <section> meet the top by scrolling. like <body class="s1"> for #s1 section and <body class="s2"> for #s2. How this can be done using jquery?

Please help.


回答1:


This is probably what you want:

http://jsbin.com/tabolida/1/edit?html,js,output

var bodyEl = $("body");
$(window).on("scroll", function() {
    var scrollTop = $(this).scrollTop();
    $("section").each(function() {
        var el = $(this),
            className = el.attr("id");
        if (el.offset().top < scrollTop) {
            bodyEl.addClass(className);  
        } else {
            bodyEl.removeClass(className);
        }
    });
});

In short: while scrolling, the offset().top of every section is checked against the scroll position of the window. If it is lower, a CSS class is added to the body; if it's higher, the CSS is removed. This could result in your body element having multiple classes:

<body class="s1 s2">

...which is solved by CSS as long as both classes have the same precedence 'points'. Also, if you have a lot of sections in your page, performance might suffer.




回答2:


You should look up

$(window).scrollTop() and $(element).offset() 

and compare those two in

$(window).scroll( function() { } );

There you can see which element is closest to the top border of the window, and act according to that.

Is that what you need?



来源:https://stackoverflow.com/questions/22017316/add-class-to-body-for-each-scrolling-based-on-section-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!