纯JavaScript:切换链接活动

时间:2017-11-24 17:13:19

标签: javascript

我的代码仅适用于第一个" a"儿童。是不是在休息" a"儿童。为什么呢?

互联网上有一些解决方案,但在jQuery中。我更喜欢纯JavaScript。



document.querySelector('a').addEventListener('click', active);

function active() {
    document.querySelector('a').classList.remove('active');
    this.classList.add('active');
}

.topnav {
  overflow: hidden;
  background-color: grey;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 10px;
  text-decoration: none;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
    background-color: red;
    color: white;
}

<div class="topnav">
  <a class="active" href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
</div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

添加id而不是class;在每次点击时删除“有效”类,然后将“有效”类添加到点击的锚标记中;

document.getElementById('news').onclick = active;
document.getElementById('home').onclick = active;
document.getElementById('contact').onclick = active;
document.getElementById('about').onclick = active;

//addEventListener('click', active);

function active() {
    document.querySelector('a.active').classList.remove('active');
    this.classList.add('active');
}
.topnav {
  overflow: hidden;
  background-color: grey;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 10px;
  text-decoration: none;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
    background-color: red;
    color: white;
}
<div class="topnav">
  <a class="active" id="home" href="#home">Home</a>
  <a href="#news" id="news">News</a>
  <a href="#contact" id="contact">Contact</a>
  <a href="#about" id="about">About</a>
</div>

答案 1 :(得分:1)

您可以将事件委派与querySelectorAll一起使用来编写如下所示的小而简洁的解决方案:

document.querySelector('.topnav').addEventListener('click', active);

function active(e) {
    document.querySelectorAll('.topnav > a').forEach(function(a){
      a.classList.remove('active');
    })
    e.target.classList.add('active');
}
  .topnav {
      overflow: hidden;
      background-color: grey;
    }

    .topnav a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 10px;
      text-decoration: none;
    }

    .topnav a:hover {
      background-color: #ddd;
      color: black;
    }

    .topnav a.active {
        background-color: red;
        color: white;
    }
  
    <div class="topnav">
      <a class="active" href="#home">Home</a>
      <a href="#news">News</a>
      <a href="#contact">Contact</a>
      <a href="#about">About</a>
    </div>
    

答案 2 :(得分:0)

您需要 querySelectorAll 和一些循环:

const menuItems = document.querySelectorAll('a');

menuItems.forEach(el =>
  el.addEventListener('click', active)
);

function active() {
  menuItems.forEach(el =>
    el.classList.remove('active')
  );
  this.classList.add('active');
}

答案 3 :(得分:0)

您应该使用document.querySelectorAll('a')