我有一个包含 6 个“部分”的页面,我正在尝试将其添加到当前部分,一旦它到达视口的顶部。但是我想要它,以便在任何时候只有 1 个部分具有“活动”类。所以我需要它来添加 'active 到当前的并从所有其他人中删除它。我可以获得第一部分,但无法将其从所有其他部分中删除?
到目前为止,这是我的代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/site.css">
<title>Home</title>
</head>
<style>
section {
height: 100vh;
padding: 100px;
display: flex;
align-items: center;
justify-content: center;
}
.section1 {
background: blue;
}
.section2 {
background: red;
}
.section3 {
background: green;
}
.section4 {
background: purple;
}
.section5 {
background: orange;
}
.section6 {
background: hotpink;
}
</style>
<body class="homepage">
<!-- Main -->
<main>
<!-- Section 1 -->
<section class="section1">
<p>Section 1</p>
</section>
<!-- Section 2 -->
<section class="section2" id="firstSection">
<p>Section 2</p>
</section>
<!-- Section 3 -->
<section class="section3">
<p>Section 3</p>
</section>
<!-- Section 4 -->
<section class="section4">
<p>Section 4</p>
</section>
<!-- Section 5 -->
<section class="section5">
<p>Section 5</p>
</section>
<!-- Section 6 -->
<section class="section6">
<p>Section 6</p>
</section>
</main>
</body>
<script src="/dev.js"></script>
</html>
JS:
function getSection() {
let sections = document.querySelectorAll('section');
for (let a = 0; a < sections.length; a++) {
let thisSection = sections[a];
let bounding = thisSection.getBoundingClientRect().top;
let height = thisSection.clientHeight;
if (bounding <= 0) {
thisSection.classList.add('active');
} else {
thisSection.classList.remove('active');
}
}
}
window.addEventListener("scroll", getSection);