为了账号安全,请及时绑定邮箱和手机立即绑定

position/getboundingclientrect 中的部分

position/getboundingclientrect 中的部分

吃鸡游戏 2023-05-25 15:35:05
我正在尝试获取部分在视口中的位置并向它们添加活动类,但代码不起作用。任何人都可以帮忙吗?// Get the position of the sections in viewportfunction 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");        }    }}
查看完整描述

1 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

let sections = document.querySelectorAll("section");

let sectionsArr = Array.from(sections);



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)

    );

  }




 function setActiveClass(){

    for (let i=0; i < sectionsArr.length; i++){

        if (isInViewport(sectionsArr[i])){

            sectionsArr[i].classList.add("your-active-class");

        }else{

            sectionsArr[i].classList.remove("your-active-class");

        }

    }}

body{

    margin:0;

}


.filler{

    width:100vw;

    height:100vh;

    background:#db9292;

    display:flex;

    align-items:center;

    justify-content:center;

}




.your-active-class{

  background:red;

}

<!DOCTYPE html>

<html>

<head>

   <meta charset="UTF-8">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <title>Document</title>

   <link rel="stylesheet" href="style.css">

</head>

<body>

   <div class="filler">

    <p class="button" onclick="setActiveClass()" >Click me!</div>

   </div>

    <section class="secs">Section1</section>

    <section class="secs">Section2</section>

    <section class="secs">Section3</section>

    <section class="secs">Section4</section>

   <script src="index.js"></script>

</body>

</html>


我猜你应该在 for 循环中将你的“sections[i]”更改为“sectionsArr[i]”并将“i <= sectionsArr.length”更改为仅“i <sectionsArr.length”


function setActiveClass(){

    for (let i=0; i < sectionsArr.length; i++){

        if (isInViewport(sectionsArr[i])){

            sectionsArr[i].classList.add("your-active-class");

        }else{

            sectionsArr[i].classList.remove("your-active-class");

        }

    }

}

查看完整回答
反对 回复 2023-05-25
  • 1 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信