我正在使用一个简单的引导顶部固定导航栏,我想改变活动页面的颜色…然而,我认为我的代码中缺少了一些东西
<div class="navbar">
<div class="navbar-fixed-top">
<div class="container" style="width: auto;">
<div class="nav-collapse" id="nav-collapse">
<ul class="nav" id="nav">
<li class="active"><a href="#skdill" >skisll</a></li>
<li class="active"><a href="#skill">skill</a></li>
<li class="active"><a href="#research">research</a></li>
<li class="active"><a href="#">Link</a></li>
</ul>
</div>
</div>
</div>
</div>
CSS是
.navbar {
position: fixed;
width: 100%;
}
.navbar .nav {
float: none;
}
.navbar .nav>li {
width: 25%;
}
.content {
padding-top: 80px;
}
#nav-collapse li a:hover {
color: blue;
}
#nav-collapse a:hover {
background-color: gray;
}
#nav-collapse li.active {
color:green;
background-color: yellow;
}
#nav-collapse li.active a {
color: red;
}
..。我想,例如,文本(的活动导航项目)是红色和背景颜色是灰色(无论什么)…你有什么想法吗?
非常感谢!
发布于 2017-06-20 23:07:44
我有一个与其他答案略有不同的答案,对我来说效果很好:
假设导航栏中的链接(在本地服务器上,https://myweburl.com将被https://localhost:8000或https://127.0.0.1:8000替换)如下:
Home => https://myweburl.com
Blog => https://myweburl.com/blog/1,https://myweburl.com/blog/2等。
Skills => https://myweburl.com/skills/
联系=> https://myweburl.com/contact/
因此,您可以使用此代码片段激活导航栏中的相应链接:
$(document).ready(function () {
var loc = window.location.href; // grabbing the url
var str = loc.split("/")[3]; // splitting the url and taking the third string
if(str.localeCompare("") == 0)
$("#home").addClass("active");
else
$("#" + str).addClass("active");
});
此外,在HTML中,删除“active”类,并在所有链接中添加相应的in。说到各自的ID,我的意思是ID应该根据URL命名。
上面的JS代码所做的事情:获取URL并将其拆分为一个字符串数组。然后,它在变量str中获取第四个字符串(第四个字符串将位于第三个索引)。然后,它将“活动”类放在该链接中。
这种方法的好处:除了它非常简单之外,如果用户直接转到链接,而不是单击导航栏中的链接,那么这种方法也可以工作。
这种方法的问题:导航栏中每个链接的URL都必须是已知的。如果URL的格式不同,那么代码中的一些更改可以帮助您。
发布于 2015-11-21 18:26:04
这个js对我很有效,我把它放在导航是php的每个页面上,包括:
<script>
$(function() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".nav li a").each(function () {
var href = $(this).attr('href');
if(path.substring((path.lastIndexOf('/')+1),path.lenght) === href) {
$(this).closest('li').addClass('active');
} else {
$(this).closest('li').removeClass();
}
});
});
https://stackoverflow.com/questions/15866136
复制相似问题