首页 > 解决方案 > 引导导航栏中的活动链接名称不会改变颜色

问题描述

这是我目前正在开发的单页网站。但是,当我单击导航栏中的另一个链接时,尽管悬停效果很好,但它并没有改变颜色。这是我的html代码:

<html>
<body>
<div class="collapse navbar-collapse justify-content-between" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 ">
<li class="nav-item ">
    <a class="nav-link scroll active " aria-current="page" href="#intro">Home</a>
</li>
<li class="nav-item">
    <a class="nav-link scroll" href="#about">About Us </a>
</li>
<li class="nav-item">
    <a class="nav-link scroll" href="#services">Services</a>
</li>
<li class="nav-item">
    <a class="nav-link scroll" href="#">Products</a>
</li>
</ul>
</div>
</html>
</body>

在此处输入图像描述

这是我的CSS:

<style>
.navbar .nav-item a {
  color: #5cbf8f !important;
}

.navbar .nav-item a:hover {
  color: #028b77 !important;
}

.navbar .nav-item a.active {
  color: #028b77 !important;
}
</style>

在此处输入图像描述

这是我的 Js:

<script>
$(document).ready(function () {
  var scrollLink = $(".scroll");

  // Smooth scrolling
  scrollLink.click(function (e) {
    e.preventDefault();
    $("body,html").animate(
      {
        scrollTop: $(this.hash).offset().top,
      },
      1000
    );
  });

  // Active link switching
  $(window).scroll(function () {
    var scrollbarLocation = $(this).scrollTop();

    scrollLink.each(function () {
      var sectionOffset = $(this.hash).offset().top - 20;

      if (sectionOffset <= scrollbarLocation) {
        $(this).parent().addClass("active");
        $(this).parent().siblings().removeClass("active");
      }
    });
  });
});
</script>

在此处输入图像描述

NB:对js不太了解,只是在网上找到的。

导航栏:

在此处输入图像描述

标签: javascripthtmlcsstwitter-bootstrap

解决方案


我认为你的 js 是错误的。

$('.active').removeClass('active');
$(this).addClass('active');

如果 DOM 层次结构已知,则可以使用更有效的选项。

例如,如果他们都是兄弟姐妹,则可以使用:

$(this).addClass('active').siblings('.active').removeClass('active');

推荐阅读