javascript - 引导导航栏中的活动链接名称不会改变颜色
问题描述
这是我目前正在开发的单页网站。但是,当我单击导航栏中的另一个链接时,尽管悬停效果很好,但它并没有改变颜色。这是我的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不太了解,只是在网上找到的。
导航栏:
解决方案
我认为你的 js 是错误的。
$('.active').removeClass('active');
$(this).addClass('active');
如果 DOM 层次结构已知,则可以使用更有效的选项。
例如,如果他们都是兄弟姐妹,则可以使用:
$(this).addClass('active').siblings('.active').removeClass('active');
推荐阅读
- php - WooCommerce:获取最新产品并(部分)随机排序
- reactjs - 如果数据为空,FetchAPI GraphQL / Gatsby 在前端抛出错误
- c# - 如何减少我的 void update() 更新次数?
- javascript - 需要在页面加载时保持切换处于活动状态,并在页面加载时将其隐藏
- dart - 有没有更好的方法通过在 Dart 中添加 2 个对象键来创建对象?
- javascript - 无法拼接对象数组中的项目
- vue.js - 如何将 Google、Facebook 和 Linkedin 登录与 nuxt js 集成
- git - 对开发人员团队的 Codespaces 设置的基数感到困惑
- c# - 如何在 C# Discord Bot 上使用 JSON API
- javascript - 测试 express.js API 的最佳方法是什么