【发布时间】:2016-02-19 13:38:14
【问题描述】:
当用户与顶部的距离不同时,我想使用 jQuery 删除/添加类。
我已经成功完成了,它工作正常,但我认为我做错了,我希望你帮助优化代码。
html 很简单,基本上是部分(包括标题)有 100% 的宽度。和不同的颜色。我想让标题在第一部分上方时改变颜色(出于美学目的)。 当页面滚动超过 1 个像素时,我还希望它有阴影。
我通过添加/删除类来做到这一点。
当我使用一个大的 else if 语句时,它不能很好地工作,因为只要匹配任何条件,js 就会停止检查其他匹配项,因此它不会应用所有需要的类。
下一个代码有效,但正如我所说,我认为它不是最佳/糟糕的编写。 这是 HTML 标记:
<header class="dark no-shadow">
Header
</header>
<section class="blue">
Please Scroll Down to see the header changes...
</section>
<section>
The header color Should change when you pass through me.
</section>
这里是 jQuery 代码:
var header = $('header'),
blueSection = $('section.blue'),
// Calculate when to change the color.
offset = blueSection.offset().top + blueSection.height() - header.height();
$(window).scroll(function(){
var scroll = $(window).scrollTop();
// Remove Class "dark" after scrolling over the dark section
if (scroll >= offset) {
header.removeClass('dark');
} else {
header.addClass('dark');
}
// Remove Class "no-shadows" whenever not on the top of the page.
if (scroll >= 1) {
header.removeClass('no-shadow');
} else {
header.addClass('no-shadow');
}
});
对于那些喜欢使用 jsfiddle 的人(比如我!): https://jsfiddle.net/shock/wztdt077/6/
谢谢各位!
【问题讨论】:
-
在此处查看滚动某处后如何执行操作 -- stackoverflow.com/questions/25660289/… -- 您可以通过 div 的位置或像素来执行操作
-
使用上面内容中的代码的演示 -- jsfiddle.net/tgaoyx4b
-
我认为你没有得到我想要做的事情,我想按以下顺序删除类:scroll > 1px = remove class "no-shadow",scroll > 120px = remove class “黑暗的”。我希望在您以相同的顺序向后滚动时添加它们。但是当我在满足第一个条件时使用“if”语句时,它会停止检查。我希望它检查所有条件,因为在其他情况下,我可能会在滚动时使用两个以上的更改。
-
我在 codereview 社区中创建了一个与此问题相同的新问题。遵循@xpy 的建议。 codereview.stackexchange.com/questions/120537/…
标签: javascript jquery if-statement scroll