[英]Can't get active navigation to work based on URL / jQuery
我有一个简单的菜单,但似乎无法使活动的导航正常工作。 我认为这可能与基于/ about的URL的代码有关,而我在链接中使用完整的URL(即http://helloarchie.blue/about )?
HTML:
<ul id="naviga">
<li><a href="http://helloarchie.blue/">Home</a>
</li>
<li><a href="http://helloarchie.blue/category/motherhood/">Motherhood</a>
</li>
<li><a href="http://helloarchie.blue/category/fashion-friday/">Fashion</a>
</li>
<li><a href="http://helloarchie.blue/category/reviews/">Reviews</a>
</li>
<li><a href="http://helloarchie.blue/category/blogging-tips/">Blogging</a>
</li>
<li><a href="http://helloarchie.blue/category/lifestyle/">Lifestyle</a>
</li>
<li><a href="http://helloarchie.blue/about/">About</a>
</li>
<li><a href="http://helloarchie.blue/contact-me/">Contact</a>
</li>
</ul>
CSS:
#naviga li {
display: inline;
padding: 0 2%;
text-align: center;
font-family:"brandon-grotesque", "HelveticaNeue", "Helvetica Neue", Helvetica, serif;
text-transform: uppercase;
letter-spacing: 3px;
font-size: 0.75em;
}
#naviga li a {
position: relative;
}
#naviga li a:hover {
color: #585858;
font-weight: bold;
}
#naviga li a::before {
content:'';
position: absolute;
background: #f6a889;
height: 2px;
margin-top: -17px;
margin-left: -2px;
top: 0;
left: 0;
width: 0%;
-webkit-transition: all 0.65s ease;
-moz-transition: all 0.65s ease;
-o-transition: all 0.65s ease;
transition: all 0.65s ease;
}
#naviga li a:hover::before {
width: 100%;
}
#naviga li a .active {
content:'';
position: absolute;
background: #f6a889;
height: 2px;
margin-top: -16px;
margin-left: -2px;
top: 0;
left: 0;
width: 100%;
}
JS:
$(document).ready(function () {
url = window.location.pathname;
url = url.substring(1);
if (url == '') {
url = 'home';
}
$('#naviga li.active').removeClass('active');
$('#naviga li').each(function () {
if ($(this).hasClass(url)) {
$(this).addClass('active');
}
});
});
您快到了,只有几个小问题:
active
CSS类设置<li>
的样式。 但是,您的CSS表示您想在<li>
内设置<a>
样式。 <li>
元素可能具有的类名进行匹配。 但是,在HTML中, <li>
元素均未分配任何类。 简而言之:给每个<li>
适当的类名(例如,“ home”)并更新CSS,以便为<li>
样式(或相应地更新JS)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.