簡體   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

    }

  }

}

應該編寫什么代碼來從其他部分刪除活動的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM