简体   繁体   中英

How to remove classname using multiple classname in JavaScript

I just trying to manipulate the class name using offsetTop and ScrollY. I have multiple div with class name of flex. I just tying to add and remove the "slide" classname using conditional statement. I can add the "slide" classname while reaching offset boundary. But I can't remove the classname after exit the boundary. Please help me for this situation. I have attached the code below.

 function GetScroll() { let FlexPositions = document.querySelectorAll(".flex"); let RemoveClass = document.querySelector("div"); FlexPositions.forEach(function(item) { if (item.offsetTop < window.scrollY + 300) { RemoveClass.classList.remove('slide') item.classList.add('slide'); } }) }
 html, body { min-height: 100%; height: 100%; padding: 0px; margin: 0px; }.flex { display: flex; height: 100%; }
 <body onscroll="GetScroll()"> <div class="flex">A</div> <div class="flex">B</div> <div class="flex">C</div> <div class="flex">D</div> <div class="flex">E</div> <div class="flex">F</div> <div class="flex">G</div> </body>

Here is working code

You need to get the element with the slide class

 window.addEventListener("load", () => { let flexPositions = document.querySelectorAll(".flex"); document.addEventListener("scroll", function() { flexPositions.forEach(item => { if (item.offsetTop < window.scrollY + 300) { document.querySelector("div.slide").classList.remove('slide') item.classList.add('slide'); } }) }) })
 html, body { min-height: 100%; height: 100%; padding: 0px; margin: 0px; }.flex { display: flex; height: 100%; }.slide { background-color: red }
 <div class="flex slide">A</div> <div class="flex">B</div> <div class="flex">C</div> <div class="flex">D</div> <div class="flex">E</div> <div class="flex">F</div> <div class="flex">G</div>

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