javascript - 带导航栏的活动菜单
问题描述
请有人能告诉我应该在这段代码中添加什么来突出显示激活页面的菜单吗?我在网上看到了很多东西,但它们没有用。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* CSS */
* {box-sizing: border-box}
body {
margin-left: 15%;
margin-right: 15%;
}
.navbar {
overflow: hidden;
background-color: #104e8B;
position: sticky;
position: -webkit-sticky;
top: 0;
border: 1px solid #ccc;
border-right: none;
}
.navbar a {
float: left;
padding: 6px;
color: white;
text-decoration: none;
font-size: 15px;
width: 20%; /* Five links of equal widths */
text-align: center;
border-left: 1px solid #fff;
border-right: 1px solid #ccc;
}
.navbar a:hover:not(.active) {
background-color: #AA0000;
color: white;
}
.navbar a:hover {
background-color: #AA0000;
color: white;
}
.active {
background-color: #10CCCC;
color: white;
}
</style>
</head>
<body>
<div class="navbar" id="Menu">
<a href="/" class="active">Home</a>
<a href="/about">About</a>
<a href="/research">Research</a>
<a href="/cv" class="right">CV</a>
<a href="/blog" class="right">Blog</a>
</div><!-- Menu-->
</body>
</html>
看来我应该添加一个script
. 我可以添加添加script
到此代码中还是应该在其他文件中?
例如,这是我添加到内容中的style
内容,但它不起作用。
<script>
$(document).ready(function() {
$('#Menu .navbar a[href="' + this.location.pathname + '"]').parent().addClass('active');
});
</script>
解决方案
- 在使用它的功能之前,你需要通过链接它的 CDN 来导入 JQuery。
- javascript 代码的惯用位置通常位于 body 标记的下部
每个按钮都有一个 id 比 this.location.pathname 更好,例如,它不适用于 jsfiddle,因为 jsfiddle 中生成的路径与 HTML 标记上的路径不同
<div class="navbar" id="Menu"> <a id='home' href="/">Home</a> <a id='about' href="/about">About</a> <a id='research' href="/research">Research</a> <a id='cv' href="/cv" class="right">CV</a> <a id='blog' href="/blog" class="right">Blog</a> </div><!-- Menu--> </body> <script> $(document).ready(function() { $('#research').addClass('active'); }); </script>
推荐阅读
- json - How to extract json data and output to csv using jq
- android - 防止系统杀死后台应用程序
- ionic-framework - ionic capacitor sign in with apple and getting name
- sql - How to user grouping sets as keys for the next grouping
- flutter - Error: The method 'ignore' isn't defined for the class 'Future
' in flutter build - sql - Why am I receiving an Error 2F0F5E42 (Missing Parenthesis) in my SQL script when it appears they are all present?
- heroku - 为什么 Heroku 找不到 jar 文件?
- three.js - Three.js 灯看起来像云纹
- javascript - ipcMain 没有从 ipcRenderer 接收任何信息
- html - 图像和文本通过边框剪裁