问题描述
我有这样的页面布局.
<body>
<section id="s1">...</div>
<section id="s2">...</div>
<section id="s3">...</div>
</body>
每当<section>
通过滚动到达顶部时,我都需要向body标签添加类.例如<body class="s1">
用于#s1
部分,而<body class="s2">
用于#s2
.如何使用jquery做到这一点?
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?
请帮助.
推荐答案
这可能是您想要的:
http://jsbin.com/tabolida/1/edit?html, js,输出
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);
}
});
});
简而言之:滚动时,将根据窗口的滚动位置检查每个部分的offset().top
.如果它较低,则将CSS类添加到主体;否则,将添加CSS类.如果更高,则删除CSS.这可能会导致您的body元素具有多个类:
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">
...只要两个类具有相同的优先级"points",CSS即可解决.另外,如果页面中有很多section
,性能可能会受到影响.
...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.
这篇关于根据部分ID为每次滚动将类添加到正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!