问题
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 section
s 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