如何根据网页部分制作自动导航栏?

How to make automatic navbar based on section of a webpage?

我遇到过两种情况,当我滚动到某个部分时,导航栏项目被自动选中。我该如何实现?我正在寻找一种最新的 2018 年解决方案,并且尽可能简单(普通 JS 或不使用额外的 JS,使用 bootstrap)。我发现了几个 post 关于使用 jquery 来做到这一点,但看起来 intersection observer 是更好的方法吗?

一个例子是https://insights.whosebug.com/survey/2018/, another is 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>

要获得动态导航links.Create一个table并添加四列,一个是每个名称显示,第二个是link(url),第三个一个是显示图标(fa fa-x) 第四个是排名顺序显示。

1.left link 标题 2.left link url 3.icon(显示图标或图像ex:fa fa-x) 4.rank(顺序排列)

将这些字段插入数据库table并在导航栏中循环显示结果。

您也可以将此 link 分配给用户,这样您就可以限制对用户的访问*。

谢谢。

where the navigation bar items are selected automatically when I scroll to certain section. How do I achieve that?

此组件在 Bootstrap 中称为 "scrollspy" 4.

来自文档:

Automatically update Bootstrap navigation or list group components based on scroll position to indicate which link is currently active in the viewport.

参考:

https://getbootstrap.com/docs/4.0/components/scrollspy/