【发布时间】:2018-09-03 21:59:22
【问题描述】:
我正在使用 Bootstrap 4 开发一个网站,该网站的部分具有浅色和深色背景以及固定的导航栏。
导航栏是深色的(具有 css 类 bg-dark),虽然在浅色部分很容易看到它,但 与深色部分没有区别。
当用户到达 dark section 时,我尝试将导航栏的 navbar-dark bg-dark 更改为 navbar-light bg-light(StackOverflow 上建议使用 solution):
$(window).on('activate.bs.scrollspy', function (e,obj) {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
return;
}
var isBGLight = $(obj.relatedTarget).hasClass('bg-light');
$('.navbar').toggleClass('navbar-dark bg-dark', isBGLight)
.toggleClass('navbar-light bg-light', !isBGLight);
});
.page-section {
padding: 70px 10px
}
.page-section.bg-dark * {
color: #fff;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<body data-spy="scroll" data-target=".navbar" data-offset="15">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
<a class="navbar-brand" href="#">Logo</a>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="about.html">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="services.html">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.html">Contact</a>
</li>
</ul>
</nav>
<div class="container-fluid bg-light page-section">
<h1>Section 1</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
<div class="container-fluid bg-dark page-section">
<h1>Section 2</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
<div class="container-fluid bg-light page-section">
<h1>Section 3</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
</body>
如您所见,我使用了 scroll-spy,但 违反了它的规则(它规定它需要锚点“指向具有 id 的元素”):我的导航栏的项目指向其他网站的页面,不到当前页面的部分。
适合上述情况的替代方案是什么?
【问题讨论】:
-
“我的导航栏项目指向网站的其他页面,而不是当前页面的部分” 这不是 scrollspy 的用途......它仅适用于相同的页面。因此,如果您链接到其他页面,您的问题“根据其悬停的 页面部分的背景更改导航栏的类”对我来说毫无意义。
-
@Themes.guide 我正在尝试匹配背景颜色。这是目标,我不喜欢滚动间谍。我只是在描述我为实现目标所做的努力。
标签: javascript jquery css bootstrap-4 scrollspy