简体   繁体   English

如果部分在视口中,则向 div 添加/删除类(vanilla JS)

[英]Add/remove class to div if section is in viewport (vanilla JS)

I have a onepager with 5 sections, each with a min-height of 100vh and an id.我有一个包含 5 个部分的单页机,每个部分的最小高度为 100vh 和一个 id。 Then there is a fixed background div that changes its state when a new section comes into the viewport.然后有一个固定的背景 div,当一个新部分进入视口时,它会改变其状态。

<div class="background"></div>

<section id="s1">...</section>
<section id="s2">...</section>
<section id="s3">...</section>
<section id="s4">...</section>
<section id="s5">...</section>

I wanted to update the background div with a class with the name of the current section id when the section enters the viewport and remove it when the section leaves the viewport.我想在该部分进入视口时使用具有当前部分 ID 名称的类更新背景 div,并在该部分离开视口时将其删除。

This is what I made:这是我做的:

const sections = document.querySelectorAll('section')
const bg = document.querySelector('div.background')

document.addEventListener('scroll', updateBg)

function updateBg() {
  sections.forEach((section) => {
    const pixels = window.pageYOffset
    const sectionId = section.getAttribute('id')
    const offsetBottom = section.offsetTop + section.offsetHeight

    if (section.offsetTop <= pixels) {
      bg.classList.add(sectionId)
    }

    else if (offsetBottom >= pixels) {
        bg.classList.remove(sectionId)
      }

    else {
      bg.classList.remove(sectionId)
    }
  })
}

Adding the current class when the section enters the viewport works fine.当部分进入视口时添加当前类工作正常。 But it's not removing the classes when the sections have left the viewport like I declared in my else if (offsetBottom >= pixels) statement.但是当这些部分离开视口时,它不会删除类,就像我在else if (offsetBottom >= pixels)语句中声明的那样。 When I fully scrolled down the page I have something like this:当我完全向下滚动页面时,我有这样的事情:

<div class="background s1 s2 s3 s4 s5"></div>

but what I want at the end is this: <div class="background s5"></div>但我最后想要的是: <div class="background s5"></div>

any help?有什么帮助吗?

Your conditions seem to be out of order.你的条件似乎不正常。 You are setting the class for all sections that are below the scroll threshold.您正在为低于滚动阈值的所有部分设置类。 Instead, you should add the class if part of the section is visible and remove it otherwise, like this:相反,如果该部分的一部分可见,您应该添加该类,否则将其删除,如下所示:

if (section.offsetTop <= pixels && offsetBottom > pixels) {
  bg.classList.add(sectionId);
} else {
  bg.classList.remove(sectionId)
}

Also, please read the answer to this question: How can I tell if a DOM element is visible in the current viewport?另外,请阅读此问题的答案: 如何判断 DOM 元素在当前视口中是否可见? It is recommended to use getBoundingClientRect API instead.建议改用getBoundingClientRect API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM