[英]Add class to section based on viewport?
我有一个包含 6 个“部分”的页面,我正在尝试制作它,以便“活动”的 class 一旦到达视口顶部就会被添加到当前部分。 但是我希望它只有 1 个部分具有“随时活动”的 class。 所以我需要它来添加 '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);
如果使用 Jquery 很容易解决。 您可以使用两个变量来保存目标 DOM 之前和之后的 DOM。 这是一个演示
for (let a = 0; a < sections.length; a++) {
let thisSection = sections[a];
const beforeSection = a > 0 ? sections[a - 1] : ''
const lastSection = a < sections.length ? sections[a + 1] : ''
let bounding = thisSection.getBoundingClientRect().top;
let height = thisSection.clientHeight;
if (bounding <= 0) {
thisSection.classList.add('active');
if (beforeSection) {
beforeSection.classList.remove('active')
}
if (lastSection) {
lastSection.classList.remove('active')
}
} else {
thisSection.classList.remove('active');
}
}
你可以试试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.