[英]How to Add Active Class to a Navigation Menu Based on URL in each page
i have a navigation menu on top of my website .that li's content many pages with different urls. 我的网站上方有一个导航菜单。李的内容很多页面都有不同的URL。 How to Add Active Class to a Navigation Menu Based on URL that in each page display it with a specific color?
如何将活动类添加到基于URL的导航菜单中,该URL在每个页面中以特定颜色显示?
<ul>
<li class="red"><a href="home">HOme</a></li>
<li><a href="gallery">gallery</a></li>
<li><a href="about">about</a></li>
<li><a href="contact">contact</a></li>
</ul>
This snippet will be useful 此代码段将很有用
HTML 的HTML
<ul id="menuList">
<li><a href="home">Home</a></li>
<li><a href="gallery">gallery</a></li>
<li><a href="about">about</a></li>
<li><a href="contact">contact</a></li>
</ul>
JS JS
$('#menuList li').click(function(e){
e.preventDefault(); //Remove this in your main code
$('#menuList li').removeClass("active");
$(this).addClass("active");
});
CSS 的CSS
.active{
background-color:green;
}
Give a class or ID to the ul
. 给
ul
一个类或ID。 Then, assuming jQuery and an ID of nav
: 然后,假设使用jQuery和ID为
nav
:
$(function() {
$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
All you need then is to style the .active
class. 然后,您只需为
.active
类设置样式.active
。 Also, this assumes your links are /my-page
, so if you are currently in my-page
, the link will become .active
. 另外,这还假设您的链接是
/my-page
,因此,如果您当前在my-page
,则该链接将变为.active
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.