简体   繁体   English

滚动事件监听器:空 While 循环,它是如何工作的,为什么?

[英]Scroll Event Listener: Empty While loop, how does it work and why?

This question is in reference to this post .这个问题参考了这篇文章

In summary, the requirement is to have the links in the navigation to change status based on the current scroll position, I was able to get the code presented here to work, but one line which I don't understand why it's done this way is总而言之,要求是让导航中的链接根据当前滚动位置更改状态,我能够使此处显示的代码正常工作,但我不明白为什么这样做的一行是

while(--index && window.scrollY + 50 < sections[index].offsetTop) {}

I would've commented on the original answer post, but apparently, my reputation is not enough yet.我会在原始答案帖子上发表评论,但显然,我的声誉还不够。

This is the whole JavaScript code这是整个 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);

Why is the while loop needed and since it's empty wouldn't it do anything?为什么需要 while 循环,既然它是空的,它不会做任何事情吗? I tried removing the while loop and it ended up breaking the code.我尝试删除 while 循环,但它最终破坏了代码。

while(--index && window.scrollY + 50 < sections[index].offsetTop) {}

This decrements the index with each iteration.这会在每次迭代时递减索引。 The loop stops when window.scrollY + 50 < sections[index].offsetTop is false, and the index remains to the value of the last 'passed' check.window.scrollY + 50 < sections[index].offsetTop为 false 时循环停止,索引保持为上次“通过”检查的值。

It is later used to update links[index].classList.add('active');它稍后用于更新links[index].classList.add('active');

It could have been written like this also:它也可以这样写:

while (index >= 0 && window.scrollY + 50 < sections[index].offsetTop) {
    index--
}

It is required to check if index has a adequate value (aka not -1 or lower), or it will error when it reached -1, as sections[-1].something does not exist.需要检查索引是否有足够的值(也就是不是 -1 或更低),否则当它达到 -1 时会出错,因为sections[-1].something不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM