[英]Scroll Event Listener: Empty While loop, how does it work and why?
这个问题参考了这篇文章。
总而言之,要求是让导航中的链接根据当前滚动位置更改状态,我能够使此处显示的代码正常工作,但我不明白为什么这样做的一行是
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
我会在原始答案帖子上发表评论,但显然,我的声誉还不够。
这是整个 JavaScript 代码
const links = document.querySelectorAll('.links');
const sections = document.querySelectorAll('section');
function changeLinkState() {
let index = sections.length;
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
links.forEach((link) => link.classList.remove('active'));
links[index].classList.add('active');
}
changeLinkState();
window.addEventListener('scroll', changeLinkState);
为什么需要 while 循环,既然它是空的,它不会做任何事情吗? 我尝试删除 while 循环,但它最终破坏了代码。
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
这会在每次迭代时递减索引。 当window.scrollY + 50 < sections[index].offsetTop
为 false 时循环停止,索引保持为上次“通过”检查的值。
它稍后用于更新links[index].classList.add('active');
它也可以这样写:
while (index >= 0 && window.scrollY + 50 < sections[index].offsetTop) {
index--
}
需要检查索引是否有足够的值(也就是不是 -1 或更低),否则当它达到 -1 时会出错,因为sections[-1].something
不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.