【发布时间】:2021-05-05 02:50:02
【问题描述】:
我想要什么? jQuery 从导航栏中动态突出显示当前页面。
我是 jQuery/HTML 的新手吗? 是的 - 如果这是一个愚蠢的问题,我们深表歉意
我是否花了数小时搜索现有的 StackOverflow 帖子却无济于事? 是的!这些是最有希望的,但由于我不明白的原因,他们的建议不起作用
- Navbar highlight for current page
- How to make css a:active work after the click?
- jQuery current page highlight
- highlighting the current page in a list of links using css / html
有什么问题? 使用下面的代码,我试图使导航栏中的当前页面(/选定部分)保持绿色突出显示(向最终用户显示他们当前所在的页面)。
悬停功能正在工作,但我似乎无法让它在单击后保持该颜色。
仅供参考 - 我在“导航菜单”中使用了 #links 和 links.html,因为我希望该解决方案适用于这两种情况(尽管实际上我将有两个单独的菜单:一个带有指向 . html 页面和一个带有页面#sections 链接的页面。
我做了一个可重复的小例子吗?见下文
index.html:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="test_main.css">
</head>
<body>
<div class="navigation">
<a href="test.html">Home</a>
<a href="#section_a">Section A</a>
<a href="#section_b">Section B</a>
</div>
<script>
$(function(){
$('a').each(function(){
if ($(this).prop('href') == window.location.href) {
$(this).addClass('active'); $(this).parents('li').addClass('active');
}
});
});
</script>
<p>Example text</p>
</body>
main.css:
/* Add a white background color to the top navigation */
.navigation {
background-color: #555555;
color: #ffffff;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.navigation a {
float: left;
background-color: #555555;
color: #ffffff;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
/* Change the color of links on hover */
.navigation a:hover {
background-color: #000000;
color: #ffffff;
}
.active {
background-color: #00ff00;
color: #00000
}
我知道这可以通过在导航类中设置 class="active" 来静态完成,但这太麻烦且不可维护。
【问题讨论】:
-
这是一个单页应用程序还是单击链接会加载一个全新的页面?
-
Re:这是一个单页应用程序吗:它不是一个单页应用程序,即有时会加载新页面,但有时导航只会将用户带到页面的不同部分(即通过a #section) 所以我尴尬地需要解决方案来处理这两种情况
标签: javascript html jquery css