简体   繁体   English

如何在 JavaScript 中使用多个类名删除类名

[英]How to remove classname using multiple classname in JavaScript

I just trying to manipulate the class name using offsetTop and ScrollY.我只是尝试使用 offsetTop 和 ScrollY 来操作 class 名称。 I have multiple div with class name of flex.我有多个 div,其中 class 名称为 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您需要使用幻灯片 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>

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

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