[英]How to remove active class from other sections
const addActiveClass = () => {
if( isInViewport(section) ) {
section.classList.add('active-section');
// How to remove the 'active-section' from other sections
}
}
}
应该编写什么代码来从其他部分删除活动的 class? 在 jQuery 中这可能很容易,但纯 js 呢?
好吧,您的问题有点令人困惑,因为没有上下文。
最简单的方法是让所有部分都有一个数组或节点 object。 然后使用 for 循环遍历这些部分,以从您想要的部分中删除活动的 class?
例如这里我有 3 个部分。 当我单击它时,我希望每个部分都有部分--active class。 但我也希望当时只有一个可以拥有该部分--active class:
<div class="section section--1 section--active"></div>
<div class="section section--2"></div>
<div class="section section--3"></div>
在 javascript 中,我将它们放在节点 object (一种数组)中:
const sections = document.querySelectorAll('.section')
然后我可以将点击事件绑定到每个部分:
sections.forEach(section => {
section.addEventListener('click', () => {
// I loop again to remove the 'section--active' from all others sections
// To avoid confusion, I use 'el' as a name for each section in sections
sections.forEach(el => el.classList.remove('section--active'))
// Then I add the 'section--active' to the clicked element
section.classList.add('section--active')
})
})
您需要首先使用document.querySelectorAll(".active-section")
遍历所有具有active-section
class 的元素并使用classList.remove()
。 然后,一旦所有元素都删除了 class,将其添加回当前有问题的元素。
这些方面的东西:
const addActiveClass = () => {
if( isInViewport(section) ) {
// Loop over all the elements that are active
document.querySelectorAll(".active-section").forEach(function(item){
item.classList.remove('active-section'); // Remove the class
});
// Then add it to the current element
section.classList.add('active-section');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.