猿问

将课程传递给两个导航栏

我正在使用两个导航栏。他们两个都共享一个类(“ navbar-item”)。基本上,两个导航栏都执行相同的操作。


例如


导航栏1


<a class="navbar-item" href="#Services">

  <span class="icon"><i class="fas fa-clipboard-list"></i></span>

  <span>Services</span>

</a>

<a class="navbar-item" href="#Delivery">

  <span class="icon"><i class="fas fa-shipping-fast"></i></span>

  <span>Delivery</span>

</a>

<a class="navbar-item" href="#Contact">

  <span class="icon"><i class="fas fa-shipping-fast"></i></span>

  <span>Contact</span>

</a>

导航栏2


<li class="navbar-item"><a href="#Services"></a></li>

<li class="navbar-item"><a href="#Delivery"></a></li>

<li class="navbar-item"><a href="#Contact"></a></li>

我想在单击时添加/删除另一个类名(“当前”)。我想将此新的类名(“当前”)添加到两个导航栏中。因此,当单击“服务”时,在两个导航栏中,只有“服务”应具有class current。单击“交付”时,在两个导航栏中,只有“交付”应具有类current。


我正在寻找一个纯粹的js解决方案(没有jQuery)。到目前为止,这就是我所拥有的。

这会将新的类名(current)仅传递给第一个导航栏。


var btns = document.getElementsByClassName("navbar-item");

for (var i = 0; i < btns.length; i++) {

  btns[i].addEventListener("click", function() {

    var current = document.getElementsByClassName("current");

    current[0].className = current[0].className.replace(" current", "");

    this.className += " current";

  });


富国沪深
浏览 135回答 2
2回答

繁星点点滴滴

注意:-这是您可以根据选定元素切换(添加/删除)类的检测div的方法。var div1 = document.getElementById("First");div1.addEventListener("click", function (e) {&nbsp; if (event.currentTarget.classList.contains('active')) {&nbsp; &nbsp; event.currentTarget.classList.remove('active');&nbsp; &nbsp; &nbsp; var element = document.getElementById("Second");&nbsp; &nbsp; &nbsp; element.classList.add("active");&nbsp; } else {&nbsp; &nbsp; event.currentTarget.classList.add('active');&nbsp; &nbsp; &nbsp; var element = document.getElementById("Second");&nbsp; &nbsp; &nbsp; element.classList.remove("active");&nbsp; }});var div2 = document.getElementById("Second");div2.addEventListener("click", function (e) {&nbsp; if (event.currentTarget.classList.contains('active')) {&nbsp; &nbsp; event.currentTarget.classList.remove('active');&nbsp; &nbsp; var element = document.getElementById("First");&nbsp; &nbsp; &nbsp; element.classList.add("active");&nbsp; } else {&nbsp; &nbsp; event.currentTarget.classList.add('active');&nbsp; &nbsp; var element = document.getElementById("First");&nbsp; &nbsp; &nbsp; element.classList.remove("active");&nbsp; }});.active{&nbsp;color:red;}<div id"newNav">&nbsp; <a class="navbar-item te" id="First" href="#Delivery">&nbsp; <span class="icon"><i class="fas fa-shipping-fast"></i></span>&nbsp; <span>Delivery</span>&nbsp; </a>&nbsp; <li class="navbar-item" id="Second"><a href="#Delivery"></a>&nbsp; &nbsp; <span>Delivery2</span>&nbsp; </li></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答