简体   繁体   English

如何从其他部分删除活动 class

[英]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

    }

  }

}

what is the code should be written to remove active class from other section?应该编写什么代码来从其他部分删除活动的 class? In jQuery this may be easy but what about pure js?在 jQuery 中这可能很容易,但纯 js 呢?

Well, you question is a bit confusing because there is no context.好吧,您的问题有点令人困惑,因为没有上下文。

The simplest approach would be to have an array or a node object with all your sections.最简单的方法是让所有部分都有一个数组或节点 object。 Then loop through theses sections with a for loop to remove the active class from the one you want?然后使用 for 循环遍历这些部分,以从您想要的部分中删除活动的 class?

For example here I have 3 sections.例如这里我有 3 个部分。 I want every section to have the section--active class when I click on it.当我单击它时,我希望每个部分都有部分--active class。 But I also want that only one at the time can have the section--active class:但我也希望当时只有一个可以拥有该部分--active class:

<div class="section section--1 section--active"></div>
<div class="section section--2"></div>
<div class="section section--3"></div>

In javascript I will get them in a node object (kind of array):在 javascript 中,我将它们放在节点 object (一种数组)中:

const sections = document.querySelectorAll('.section')

Then I can bind click event to each 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')
  })
})

You'll need to first loop over all the elements that have the active-section class with document.querySelectorAll(".active-section") and use classList.remove() .您需要首先使用document.querySelectorAll(".active-section")遍历所有具有active-section class 的元素并使用classList.remove() Then, once all elements have had that class removed, add it back to just the current element in question.然后,一旦所有元素都删除了 class,将其添加回当前有问题的元素。

Something along these lines:这些方面的东西:

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.

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