Bootstrap 4 - Scrollspy not working

2019-06-28 04:56发布

问题:

I have followed the documentation on how to use Scrollspy in BS4, but it is not working, so how do I solve it?

My body has posistion: relative

This is my body tag:

<body data-spy="scroll" data-target=".navbar">

And this is the HTML for the navbar:

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="container">

        <a class="navbar-brand" href="/">
            <img src="/images/logo_placeholder.jpg" width="90" height="45" class="d-inline-block align-top" alt="">
            Jalinen
        </a>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" href="#home">Home </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Nieuws</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Diensten</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Calamiteiten</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Gallerij</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

Why is it not working?

Note:

Nothing works atm.

The navbar doesn't even stick to the top of the page.

回答1:

Make sure you're using fixed-top to attach the navbar to the top,

<nav class="navbar navbar-toggleable-md fixed-top navbar-light bg-faded">
  ..
</nav>

and the body tag:

<body data-spy="scroll" data-target="#navbar1" data-offset="70">

Bootstrap 4 Scrollspy Demo

EDIT: navbar-toggleable-md has changed to navbar-expand-lg in Bootstrap 4.0.0



回答2:

You content sections must have unique ID (#about) which is connected to an anchor in the navigation. (Your #home ID is valid only)

Correct:

            <li class="nav-item active">
                <a class="nav-link" href="#home">Home </a>
            </li>

Wrong:

            <li class="nav-item">
                <a class="nav-link" href="#">Nieuws</a>
            </li>