我遇到两种情况,当我滚动到某个部分时会自动选择导航栏项目。我该如何做到这一点?我正在寻找一个 2018 年最新且尽可能简单的解决方案(vanilla JS 或没有使用 bootstrap 的额外 JS)。我发现了几篇关于使用 jquery 来做到这一点的帖子,但看起来交叉点观察者是更好的方法?
一个例子是https://insights.stackoverflow.com/survey/2018/,另一个例子是http://getbootstrap.com/docs/3.3/javascript/#dropdowns。
假设我有以下 html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="navbar">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active" id="about-nav-item">
<a class="nav-link" href="#about">About <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" id="portfolio-nav-item">
<a class="nav-link" href="#portfolio">Portfolio</a>
</li>
<li class="nav-item" id="contact-nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</nav>
<div class="container" id='about'>
</div>
<div class="container" id='portfolio'>
</div>
<div class="container" id='contact'>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script type="text/javascript" src="code.js"></script>
</body>
</html>