首页 > 解决方案 > 带导航栏的活动菜单

问题描述

请有人能告诉我应该在这段代码中添加什么来突出显示激活页面的菜单吗?我在网上看到了很多东西,但它们没有用。

<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>

标签: javascriptjqueryhtmlcss

解决方案


  1. 在使用它的功能之前,你需要通过链接它的 CDN 来导入 JQuery。
  2. javascript 代码的惯用位置通常位于 body 标记的下部
  3. 每个按钮都有一个 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>
    

https://jsfiddle.net/skwn50dj/


推荐阅读