[英]jquery, add active class to links
Hi i'm working on a off canvas menu and I want to add a class to highlight active menu item but the jquery code I'm currently working with does not seem to add the class to the active link. 嗨,我正在关闭画布菜单上工作,我想添加一个类来突出显示活动菜单项,但是我当前正在使用的jquery代码似乎并未将该类添加到活动链接中。 I tried all potential solutions I came across in the web and nothing seem to work.
我尝试了所有在网络上遇到的潜在解决方案,但似乎没有任何效果。 Any suggestions, ideas, resources?
有什么建议,想法,资源吗?
<nav class="site-menu">
<div class="menu-list">
<ul>
<li><a href="portfolio.php">portfolio</a></li>
<li><a href="projects.php">projects</a></li>
<li><a href="process.php">process</a></li>
<li><a href="blog.php">blog</a></li>
<li><a href="contact.php">contact</a></li>
</ul>
</div>
</nav>
css 的CSS
.site-menu ul {
list-style: none;
padding: 20px;
margin: 0;
}
.site-menu ul li a {
display: block;
width: 100%;
height: 50px;
line-height: 50px;
color: #7f7f7f;
background: transparent;
text-decoration:none;
}
.menu-list{
position: absolute;
top: 80px;
margin-left: 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
text-transform: uppercase;
letter-spacing: 2px;
text-align: left;
}
.active {
color:#fff;
}
script 脚本
var selector = ".site-menu li";
$(selector).click(function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
You need to make CSS selector more specific: 您需要使CSS选择器更具体:
.site-menu ul li.active a {
color: #fff;
}
Otherwise the rule .site-menu ul li a
has higher precedence. 否则规则
.site-menu ul li a
具有更高的优先级。
Read on the subject: CSS Specificity: Things You Should Know . 阅读以下主题: CSS特殊性:您应该知道的事情 。
Try this: 尝试这个:
var selector = ".site-menu li";
selector.click(function(){
selector.removeClass('active');
$(this).addClass('active');
});
您必须将选择器更改为以下选择器:
var selector = ".site-menu ul li a";
When you load a new page the javascript changes will be lost. 当您加载新页面时,javascript更改将丢失。 But you can check what page is
active
when the page is loaded like this: 但是您可以像这样检查页面加载时
active
状态的页面:
JS JS
(function($){
$('.site-menu li a').each(function(){
if( $(this).attr('href') == window.location.pathname ) $(this).addClass('active');
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.