使用 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);

});


BIG阳
浏览 102回答 1
1回答

桃花长相依

entry.isIntersecting直接用于classList.toggle()第二个(布尔)参数。使用 options {threshold: 0},或者根本不使用,因为阈值默认为0const check = (entries) => entries.forEach(entry => {&nbsp; 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 {&nbsp; min-height: 100vh;&nbsp; transition: 0.5s;&nbsp; transform: scale(0.4);&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; align-items: center;&nbsp; font-size: 70vh;}.is-active {&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript