首页 > 解决方案 > 如何使用 jquery 在导航栏下划线

问题描述

@ikiK 我尝试实施您的解决方案,但没有奏效。我所有的文件都在同一个文件夹中,html文件称为index.html,css文件称为style.css,jquery文件称为script.js我不知道我做错了什么,所以如果你可以指导我如何解决它,将不胜感激。

$("a").click(function(){
    $("a.active-menu").removeClass("active-menu");
    $(this).addClass("active-menu");
 });
*{
    margin:0;
    padding:0;
    border:0;
}


.topnav {
    background-color: purple;
    overflow: hidden;
  }
  
  .topnav a {
    float: left;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    position: relative;
  }

  .topnav a:before {
    content: "";
    position: absolute;
    width: 84%;
    height: 2px;
    bottom: 3px;
    left: 8%;
    background-color: white;
    visibility: hidden;
    transform: scaleX(0);
    transition: all 0.3s ease-in-out 0s;
  }

 .topnav a:hover:before {
    visibility: visible;
    transform: scaleX(1);
  }
.topnav a.active-menu:before {
    content: "";
    position: absolute;
    width: 84%;
    height: 2px;
    bottom: 3px;
    left: 8%;
    background-color: white;
    visibility: visible;
    transform: scaleX(1);
    transition: all 0.3s ease-in-out 0s; 
    }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
  <title>
    Change
  </title>
</head>

<body>
  <div class="topnav" id="topnav">
    <a class="active-menu" href="index.html">Home</a>
    <a class="link" href="#news">DontUse</a>
    <a class="link" href="#contact">DontUse</a>
    <a class="link" href="about.html">About</a>
  </div>
  <p>
    This is the home page
  </p>
</body>

</html>

标签: htmljquerycss

解决方案


我看到的第一个问题}在第一个片段中太多了。它过早地关闭了该功能。它应该是:

$("a").click(function(){
    $("a.active-menu").removeClass("active-menu");
    $(this).addClass("active-menu");
});

推荐阅读