简体   繁体   English

将活动 class 添加到导航栏

[英]Adding an active class to the navbar

This is how my code looks like:这就是我的代码的样子:

<div class="header-nav navbar-collapse collapse ">
      <ul id="navigation" class=" nav navbar-nav">       
                   <li>
                        <a href="index.html">Home</a>
                                
                   </li>
                            
                    <li>
                        <a href="about-us.html">About Us</a>
                    </li>
                     
                    </ul>
                    </div>

I've been trying to add the active class to each of them when the user is on that specific page but no succes so far Tis is how my script looks like:当用户在该特定页面上但到目前为止没有成功时,我一直在尝试将活动的 class 添加到每个人中,这就是我的脚本的样子:

     var i = 0;
  [].forEach.call(document.querySelectorAll('li > a'), function(nav) {
    console.log(nav.pathname,window.location.pathname);
    if (nav.pathname === window.location.pathname){
        i = 1;
        console.log(i);
      nav.classList.add('active')
    }
        
    else{
         console.log(i)
         nav.classList.removeClass('active')
  }
    

  })           

The active class is set on the "a" not on "li" and i don't know how to fix this.活动的 class 设置在“a”而不是“li”上,我不知道如何解决这个问题。 Maybe someone can help me?也许有人可以帮助我?

To target the parent element, you have a few options - my favorite is element.closest(selector) which takes a starting element and finds the closest containing parent that matches selector要定位父元素,您有几个选项 - 我最喜欢的是element.closest(selector) ,它接受一个起始element并找到与selector匹配的closest的包含父元素

 let els = document.querySelectorAll('li > a'); els.forEach(el => { el.addEventListener('click', e => { els.forEach(a => a.closest('li').classList.remove('active')); e.target.closest('li').classList.add('active'); }) })
 li.active { background-color: green; }
 <ul> <li><a href='#'>link 1</a></li> <li><a href='#'>link 1</a></li> <li><a href='#'>link 1</a></li> </ul>

In looking at the classes, it looks like you may be using Bootstrap.在查看这些类时,您可能正在使用 Bootstrap。 I added in those libs to the snippet, and updated some of the classes.我将这些库添加到片段中,并更新了一些类。 I also added in another nav item with the href equal to js since that is the pathname for the snippet window.我还添加了另一个导航项,其 href 等于js ,因为这是片段 window 的路径名。 Otherwise it won't add the active class as there would not be a pathname that would be equal.否则它不会添加活动的 class 因为不会有一个相同的路径名。

I also changed the nav items to pills, so you can see the active link easier.我还将导航项目更改为药丸,因此您可以更轻松地查看活动链接。

 var i = 0; document.querySelectorAll('ul.nav > li > a').forEach((nav) => { console.log({ navPathname: nav.pathname, windowLocationPathname: window.location.pathname, areEqual: nav.pathname === window.location.pathname, }); if (nav.pathname === window.location.pathname) { nav.classList.add('active') } else { nav.classList.remove('active') } })
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <div class="navbar navbar-light bg-light"> <ul id="navigation" class="nav nav-pills"> <li class="nav-item"> <a class="nav-link" href="index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="js">JS</a> </li> <li class="nav-item"> <a class="nav-link" href="about-us.html">About Us</a> </li> </ul> </div>

Thanks for this, i merged the two responses and made it into one that works for me, this is the script that worked without even touching the classes into the nav-bar:感谢这一点,我将这两个响应合并为一个对我有用的响应,这是一个脚本,它甚至不需要将类接触到导航栏中:

    document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
    console.log({
      navPathname: nav.pathname,
      windowLocationPathname: window.location.pathname,
      areEqual: nav.pathname === window.location.pathname,
    });
  if (nav.pathname === window.location.pathname) {
    nav.closest('li').classList.add('active')
  } else {
    nav.closest('li').classList.remove('active')
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM