简体   繁体   中英

add class to element in viewport

I have five sections on my page, and I am trying to add class "active" to the section in the view port. I tried this code but it is not working properly. the code saves all elements with tag name "section" in a node list then created an array of this list, I looped over the array and added an event listener for each element, then I tested if the element is in the viewport is so I add the class else I remove the class. the problem is once the page is scrolled all the five sections will have the class "active" which means that multiple elements have the class "active" at the same time even though only one section is viewed in the port and when I keep on scrolling down the sections that are moved upward out of the viewport have their class "active" removed. how can i have one element with the class "active" image of code at a time?

//values of viewport
const viewWidth = document.documentElement.clientWidth;
const viewHeight = document.documentElement.clientHeight;

//set class active to section in viewport
function sectionInView(x) {
    for (let i = 0; i in x; i++) {
        document.addEventListener("scroll", function () {
            let el = x[i].getBoundingClientRect();
            if (el.top >= 0 && el.left >= 0 && el.bottom <= viewHeight && el.right <= viewWidth) {
                x[i].setAttribute("class", "active your-active-class");

            }
            else {

                x[i].removeAttribute("class", "active your-active-class");
            }
        });
    }
}
sectionInView(sectionListArray);

 let sectionListArray = document.querySelectorAll('section') const viewHeight = document.documentElement.clientHeight window.onscroll = (() => { sectionListArray.forEach(function(v) { let rect = v.getBoundingClientRect(); let y = rect.y; let bottom = rect.bottom; let height = rect.height; if (y > window.innerHeight || bottom+height < window.innerHeight ) { v.classList.add('active') } else { v.classList.remove('active') } }) })
 section { height: 300px; background: red; margin-bottom: 10px; transition: 1s; opacity:1 } .active{ opacity:0 }
 <section></section> <section></section> <section></section> <section></section> <section></section> <section></section> <section></section> <section></section> <section></section>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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