简体   繁体   中英

How Can I Make A Dynamic Navbar

I would like to make my navbar dynamic so that when I am on that selected page the class active is added. I know I can do as bellow, however, is there a simpler way even with Javascript so that I don't need to copy and paste a bunch of times?
(maybe with a different class?)

$a='home';

<nav>
  <a href="#" class="nav-link <?php if($a==Home) echo 'active';?>">home</a>
</nav>

this is a JavaScript salutation:

 <!doctype html> <html> <head> <style> .active { color: red; } </style> </head> <body> <a href="js" class="nav-item">Curent Page</a> <a href="page2.html" class="nav-item">Difrent Page</a> <a href="page3.html" class="nav-item">Difrent Page</a> <script> var navClass = document.getElementsByClassName("nav-item"); var path = window.location.href; for (i = 0; i < navClass.length; i++) { if (path.includes(navClass[i].href)) { navClass[i].classList.add("active"); } } </script> </body> </html> 
it takes the content of the href and sees if it is included in curent url if yes it adds a class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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