首页 > 解决方案 > 使用 Intersection Observer 切换活动类

问题描述

我试图在滚动页面时更改我的部分的活动类。我正在使用intersectionObserver,但我感觉很坚持。我需要从 activeId 获取 activeElement,但不确定如何执行此操作。

这是我得到的解码代码:

const options = {
    threshold: 0.75
}

let observer = new IntersectionObserver(check, options);

function check(entries) {
    entries.forEach(entry => {
        const activeId = entry.target.id;
        const activeElement = 

    if(entry.isIntersecting){
        activeElement.classList.toggle("your-active-class");
    };
});
};

sections.forEach(section => {
    observer.observe(section);
});

标签: javascript

解决方案


  • entry.isIntersecting直接用于您的第二classList.toggle()个(布尔)参数。
  • 使用 options {threshold: 0},或者根本不使用,因为threshold默认为0

const check = (entries) => entries.forEach(entry => {
  entry.target.classList.toggle("is-active", entry.isIntersecting);
});

const Obs = new IntersectionObserver(check);
document.querySelectorAll("section").forEach(el => Obs.observe(el));
* {margin:0; box-sizing: border-box;}

section {
  min-height: 100vh;
  transition: 0.5s;
  transform: scale(0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 70vh;
}

.is-active {
  transform: scale(1);
}
<section style="background: #0bf;">1</section>
<section style="background: #f0b;">2</section>
<section style="background: #fb0;">3</section>
<section style="background: #0fb;">4</section>


推荐阅读