Установите мои ссылки на панель навигации начальной загрузки активными (с чистым JavaScript)

#javascript #html #css #bootstrap-4

#javascript #HTML #css #bootstrap-4

Вопрос:

Я пытаюсь сделать так, чтобы мои ссылки на панели навигации становились активными при нажатии. Я полагаю, что я бы сделал это, добавив класс active при нажатии; однако я не уверен, как остановить текущую активную ссылку от активности. Кроме того, я не уверен

 let links = document.querySelectorAll('.nav-link');

links.addEventListener('click', function() {
    this.classList.add('active');
});
  

Кроме того, у меня есть это для того, чтобы сделать ссылку активной; однако я не могу запустить ее после запуска html, поэтому она не работает.

https://jsfiddle.net/ysejr17L/2/

TL; DR

  • не знаю, как заставить JS найти текущую активную ссылку и удалить ее активный класс
  • код для активации ссылки, на которую нажимают, загружается перед HTML, поэтому он не работает

Ответ №1:

Посмотрите этот фрагмент:

 let links = document.querySelectorAll('.nav-link');
for(let i=0; i<links.length; i  ){
  links[i].addEventListener('click', function() {
    for(let j=0; j<links.length; j  )
      links[j].classList.remove('active');
    this.classList.add('active');
  });
}  
 body {
  background: linear-gradient(0.1turn, #673fa6, #e1f5f8, #f6c43c);
}

nav {
  opacity: 0.8;
}

.text-shadow {
  text-shadow: 5px 5px 15px;
}  
 <!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <!-- My CSS -->
  <link rel="stylesheet" href="styles/style.css">

  <title>Justice Dunn</title>
</head>
<body>
  <nav class="navbar navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">
      <img src="node_modules/bootstrap-icons/icons/kanban-fill.svg" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy">
      Justice Dunn
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link active" href="#bg1">Home</a>
        <a class="nav-link" href="#bg2">Background</a>
        <a class="nav-link" href="#bg3">Hobbies</a>
        <a class="nav-link" href="#bg4">Achievements</a>
        <a class="nav-link" href="#bg5">The Future</a>
        <a class="nav-link" href="#bg6">Gallery</a>
      </div>
    </div>
  </nav>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg1">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-shadow display-3">Hello!</h1>
      <p class="text-center text-shadow h4">I'm Justice Dunn, a 19-year-old developer in Cheyenne, Wyoming.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg2">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Background</h1>
      <p class="text-center text-black mt-3 h5">I decided that I wanted to become a developer for a few reasons.</p>
      <p class="text-center text-black mt-3 h5">I've always been a creative person, and I've always enjoyed problem solving. Being a developer just seems to be an occupation that naturally incorporates both of those things.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg3">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Hobbies</h1>
      <p>Writing Music</p>
      <p>Digital Art</p>
      <p>3D Modeling</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg4">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Achievements</h1>
      <p class="text-center h5 mt-3">I don't have a lot of life experience yet, so I'd say my greatest achievement was getting accepted into the Array apprenticeship program!</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg5">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">The Future</h1>
      <p class="text-center h5 mt-3">After this Array apprenticeship, I want to begin developing apps and write, record, and produce an album.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg6">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Gallery</h1>
      
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS and local JS -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV rV" crossorigin="anonymous"></script>
  <script src="/scripts/script.js"></script>
</body>
</html>  

Мы добавляем прослушиватель событий щелчка к каждому элементу class .nav-link , который сначала удаляет .active class из всех элементов, а затем добавляет class .active к элементу, на который нажимается.

Ответ №2:

Вы могли бы попробовать это также без использования цикла при каждой загрузке.

   document.body.addEventListener('click', function(e) {
  if(e.target.className==='nav-link'){
      document.getElementsByClassName('nav-link active')[0].classList.remove('active');
     e.target.classList.add('active');
     }
  });  
 body {
  background: linear-gradient(0.1turn, #673fa6, #e1f5f8, #f6c43c);
}

nav {
  opacity: 0.8;
}

.text-shadow {
  text-shadow: 5px 5px 15px;
}  
 <!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <!-- My CSS -->
  <link rel="stylesheet" href="styles/style.css">

  <title>Justice Dunn</title>
</head>
<body>
  <nav class="navbar navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">
      <img src="node_modules/bootstrap-icons/icons/kanban-fill.svg" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy">
      Justice Dunn
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link active" href="#bg1">Home</a>
        <a class="nav-link" href="#bg2">Background</a>
        <a class="nav-link" href="#bg3">Hobbies</a>
        <a class="nav-link" href="#bg4">Achievements</a>
        <a class="nav-link" href="#bg5">The Future</a>
        <a class="nav-link" href="#bg6">Gallery</a>
      </div>
    </div>
  </nav>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg1">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-shadow display-3">Hello!</h1>
      <p class="text-center text-shadow h4">I'm Justice Dunn, a 19-year-old developer in Cheyenne, Wyoming.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg2">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Background</h1>
      <p class="text-center text-black mt-3 h5">I decided that I wanted to become a developer for a few reasons.</p>
      <p class="text-center text-black mt-3 h5">I've always been a creative person, and I've always enjoyed problem solving. Being a developer just seems to be an occupation that naturally incorporates both of those things.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg3">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Hobbies</h1>
      <p>Writing Music</p>
      <p>Digital Art</p>
      <p>3D Modeling</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg4">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Achievements</h1>
      <p class="text-center h5 mt-3">I don't have a lot of life experience yet, so I'd say my greatest achievement was getting accepted into the Array apprenticeship program!</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg5">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">The Future</h1>
      <p class="text-center h5 mt-3">After this Array apprenticeship, I want to begin developing apps and write, record, and produce an album.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg6">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Gallery</h1>
      
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS and local JS -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV rV" crossorigin="anonymous"></script>
  <script src="/scripts/script.js"></script>
</body>
</html>