1 回答
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");
}
}
}
添加回答
举报