简体   繁体   中英

Issue with tab links disappearing when clicking elsewhere on the page

I'm new to Javascript and I'm having problem with the tab links set on my webpage.

The links cycle trough and display the appropriate content, however, when it comes to adding the styling of the active button, on loading the page the underline shows correctly and clicking elsewhere keeps it in place, but if I click on the other links and then click elsewhere the styling disappear.

The full code is here https://codepen.io/Rei89/pen/VwBrJEr

this is the piece I'm having trouble with:

const tabsContainer = document.getElementById("links");
const tabs = tabsContainer.getElementsByClassName("tablinks");  

  for (let i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", () => {
    let current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";    
    });
  };

You can add and remove classes using javascript like this. Before adding 'active' class, remove that from all 'tablinks'.

const tabsContainer = document.getElementById("links");
const tabs = tabsContainer.getElementsByClassName("tablinks");     
// Loop through the buttons and add the active class to the current/clicked button
  for (let i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", () => {
    removeClasses();
    tabs[i].classList.add("active");
    });
  };
  
var els = document.querySelectorAll('.tablinks')
function removeClasses() {
  for (var i = 0; i < els.length; i++) {
    els[i].classList.remove('active')
  }
}

You can use other methods such as remove and add:D

const tabsContainer = document.getElementById("links");
const tabs = tabsContainer.getElementsByClassName("tablinks"); 

for (let i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", () => {
    let current = document.getElementsByClassName("active")[0];
      current.classList.remove("active");
      tabs[i].classList.add("active");
    });
  };

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