Javascript 位置中的节/getboundingclientrect

Javascript 位置中的节/getboundingclientrect,javascript,html,css,Javascript,Html,Css,我正在尝试获取视口中各部分的位置&向它们添加一个活动类,但代码不起作用。有人能帮忙吗 // Get the position of the sections in viewport function isInViewport(element) { const rect = element.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 &

我正在尝试获取视口中各部分的位置&向它们添加一个活动类,但代码不起作用。有人能帮忙吗

// Get the position of the sections in viewport

function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

//add active class to sections in viewport
 function setActiveClass(){
    for (let i=0; i <= sectionsArr.length; i++){
        if (isInViewport(sections[i])){
            sections[i].classList.add("your-active-class");
        }else{
            sections[i].classList.remove("your-active-class");
        }
    }
}

//获取节在视口中的位置
函数isInViewport(元素){
const rect=element.getBoundingClientRect();
返回(
rect.top>=0&&
rect.left>=0&&
直肠底部
let sections=document.queryselectoral(“section”);
设sectionsArr=Array.from(节);
函数isInViewport(元素){
const rect=element.getBoundingClientRect();
返回(
rect.top>=0&&
rect.left>=0&&

我尝试了各个部分之间的所有变化§ionsArr,但仍然没有检测到类,但无法检测问题在哪里。请再次查看答案,您在for循环中出现了一个小错误。(更改iyes当然!我感谢您的帮助,但是导航菜单没有显示在代码笔中,但它出现在所有浏览器中。这是个错误。非常感谢您,我是Javascript初学者,需要大量练习。我感谢您花时间帮我。