如何使重定向<li>到新页面时保持突出显示?



我正在尝试在我的索引中调用导航栏(navbar.html.html。导航栏.html有自己的 css,在导航栏中.html是一个脚本,可以在按下<a>时更改<li>类。

我已经设法使<li>更改突出显示,但是当我按下<a>时,新页面上不会突出显示。

索引.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<title></title>
</head>
<body>
<!--NAVIAGTION BAR-->
<div id="navbar-placeholder">

</div>

<script>
$(function(){
$("#navbar-placeholder").load("Files/navbar.html");
});
</script>
<!--END OF NAVIGATION BAR-->
</body></html>

导航栏.html

<link rel="stylesheet" href="css/navbar.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div class="navigation">
<ul>
<li class=""><a href="work.html">Work</a></li>
<li class="active"><a href="index.html">Home</a></li>
<li class=""><a href="contact.html">Contact</a></li>
</ul>
</div>

<script>
$(document).ready(function() {
$(".navigation li").click(function() {
$(".navigation li").removeClass("active");
$(this).addClass("active");
});
});
</script>

导航栏.css

.navigation{
position: fixed;
top: 0;
width: 100%;
background-color:#262126;
text-align: center;
}
.navigation ul{
margin: 0;
}
.navigation li{
display: inline-block;
padding: 15px 30px;
margin: 10px 5px 0px 5px;
text-decoration: none;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
}
.navigation a{
color: white;
text-decoration: none;
text-transform: capitalize;
}
.navigation li:hover{
background-color: #F2F2F2;
transition: 0.4s;
}
.navigation li:hover a{
color: black;
}
.navigation li.active{
background-color: #F2F2F2;
}
.navigation li.active a{
color: black;
}

逻辑是倒退的。 在发生单击时添加类毫无意义,因为您将立即离开该页面

当每个页面加载时,将当前location.href与链接匹配,然后添加类。

var $navItems = $(".navigation li").removeClass("active"); 
$navItems.filter(function(){
return $(this).find('a').prop('href') === location.href;
}).addClass("active");

最新更新