关于你实际问的问题......
...这是如何循环遍历集合的:
您有很多选择,其中大部分都在这个答案在“对于类数组对象”下 https://stackoverflow.com/a/9329476/157247.
简而言之,一些选择,假设我们从以下开始:
var myCollection = document.getElementsByClassName("navBarLink");
forEach
:
// forEach:
Array.prototype.forEach.call(myCollection, function(element) {
// Use element here
});
for
loop:
var i;
for (i = 0; i < myCollection.length; ++i) {
// Use myCollection[i] here
}
请注意,这是0
通过< myCollection.length
, not <= myCollection.length
.
或者使用获取一个真正的数组Array.from
or Array.prototype.slice
。链接答案中的详细信息。
关于你实际上在做什么......
I would strongly建议您不要做大量的内联样式。相反,您的 JavaScript 可以如此简单:
window.addEventListener('scroll', function (evt) {
var distance_from_top = document.body.scrollTop;
document.body.classList.toggle("near-top", distance_from_top <= 80);
document.body.classList.toggle("not-near-top", distance_from_top > 80);
});
(如果您必须支持非常旧的浏览器,您将需要一个classList
垫片或只是操纵body.className
直接地。)
然后,在 CSS 中完成其余部分,例如#navBar
stuff:
body.not-near-top #navBar {
/* styles for when we're not near the top */
}
body.near-top #navBar {
/* style for when we are near the top */
}
从技术上讲,如果您愿意,您可以取消其中一个类,只需基于样式body #navBar { ... }
然后在您保留的课程中覆盖。