简体   繁体   English

如何制作动态导航栏

[英]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. 我想使导航栏动态化,这样当我在所选页面上时,将添加active类。 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? 我知道我可以做下面的事情,但是,即使使用Javascript,也有没有更简单的方法,这样我就不需要复制和粘贴很多次了?
(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: 这是一个JavaScript称呼:

 <!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 它接受href的内容,并查看它是否包含在当前URL中(如果是),它添加了一个类

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

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