簡體   English   中英

滾動事件監聽器:空 While 循環,它是如何工作的,為什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM