在链接上切换活动类

时间:2018-04-03 15:37:06

标签: javascript

如果脚本在两个类之间切换,我还会在当前选定的链接中添加一个活动状态,以设置下划线以显示活动状态。但是,当连续单击链接时,它会不断添加活动类,而不是打开和关闭类。如何在单击链接时显示活动状态,并在单击其他链接时关闭并应用于其他链接?

JS

const Terms = {
  bindEvents () {
this.enTrigger.addEventListener('click', (e) => {
  this.langToggle(this.englishContent)
  this.enTrigger.classList.add('active')
    this.frTrigger.classList.remove('active')
})
this.frTrigger.addEventListener('click', (e) => {
  this.langToggle(this.frenchContent)
  this.frTrigger.classList.add('active')
    this.enTrigger.classList.remove('active')
})
  },

  init () {
    this.englishContent = document.getElementById('english-terms')
    this.frenchContent = document.getElementById('french-terms')
    this.enTrigger = document.getElementById('en')
    this.frTrigger = document.getElementById('fr')
    this.bindEvents()
  },

  langToggle (id) {
    this.englishContent.style.display = 'none'
    this.frenchContent.style.display = 'none'
    id.style.display = 'block'
  }
}

document.addEventListener('DOMContentLoaded', () => {
  Terms.init()
})

HTML

<div class="terms-nav">
  <a id="en">English</a><a id="fr">French</a>
</div>

1 个答案:

答案 0 :(得分:0)

你可以尝试使用这样的东西在两个类之间切换。因此,当您单击一个元素时,它会将该类添加到自身,但会将其从另一个元素中删除。 JS Fiddle

var english = document.getElementById('en');
var french = document.getElementById('fr');


english.addEventListener('click', function(){
    this.classList.add('active');
    french.classList.remove('active');
});

french.addEventListener('click', function(){
    this.classList.add('active');
    english.classList.remove('active');
});