我有一个简单的菜单,但我似乎无法使用事件导航。我认为这可能与基于 URL 的代码有关/about 而我在我的链接中使用完整的 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');
}
});
});
最佳答案
您快完成了,只是几个小问题:
- 您的 JS 似乎暗示您想要设置
<li>
的样式与active
CSS 类。但是,您的 CSS 暗示您想要设置<a>
的样式。在<li>
内. - 您正在将 URL 与
<li>
的类名进行匹配元素可能有。但是,在您的 HTML 中,没有一个<li>
元素具有分配给它们的类。
简而言之:给每个 <li>
适当的类名(例如,'home')并更新您的 CSS,以便 <li>
设置样式(或相应地更新 JS)。
关于jquery - 无法根据 URL/jQuery 进行主动导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33755038/