[英]Bootstrap navbar menu item li a change the active class when in the specific page
Using pure CSS and some javascript, how can I manage to remove and add the class 'active' to my li item?使用纯 CSS 和一些 javascript,我如何才能删除类“active”并将其添加到我的 li 项中? I tried using the 'onclick' function in javascript.我尝试在 javascript 中使用“onclick”函数。 It changes the color of the item but it doesn't redirect me to the link of my the selected item.它会更改项目的颜色,但不会将我重定向到所选项目的链接。
<div class="main_navs">
<ul class="nav navbar-nav">
<li><a href="index.php" class="main_navmenu active">Home</a></li>
<li><a href="product.php" class="main_navmenu">Products</a></li>
<li><a href="services.php" class="main_navmenu">Services</a></li>
<li><a href="account.php"> Wishlist</a></li>
<li><a href="login.php"> Register</a></li>
<li><a href="gift_card.php"> Gift Card</a></li>
<li><a href="cart.php" class="main_navmenu"
<i class="fa fa-shopping-cart"></i> Cart <span class="badge">0</span></a></li>
</ul>
</div>
<script type="text/javascript">
$('#main_menu_items li a').on('click', function(){
$('li a.active').removeClass('active');
$(this).addClass('active');
});
</script>
CSS: CSS:
.main_navs ul li a.active{
background: rgba(255,255,255,0.2);
color: #333;
}
.main_navs ul li a{
background: rgba(0,0,0,1);
color: #fff;
}
I think this should help you out.我想这应该能帮到你。 It should add the class active to the matching anchor in your menu on page load.它应该在页面加载时将活动类添加到菜单中的匹配锚点。
<script>
$(function() {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.main_navs a').each(function() {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});
});
</script>
Remove trailing slash first and then it would equal to the url that you want to match.首先删除尾部斜杠,然后它将等于您要匹配的 url。
My solution is:我的解决办法是:
var current = window.location.href;
var current_url = current.replace(/\/$/, "");
$('.navbar-nav a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current_url) !== -1){
$this.addClass('active');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.