Я пытаюсь изменить цвет фона элемента навигационной панели Bootstrap при прокрутке из-за раздела, на который ведет ссылка (в настоящее время он работает только по щелчку). Я читал о Scrollspy, но у меня это не работает. Любая помощь будет оценена :)

Код:

$(document).ready(function ()
{ 
    $('ul.navbar-nav > li').click(function(e)
    { 
        $('ul.navbar-nav > li').removeClass('active'); 
        $(this).addClass('active');
    });

    $('#logo').click(function(e)
    {
        $('ul.navbar-nav > li').removeClass('active');
    })
});
.navbar
{
    padding: 0.8rem;
    background-color: #1C2331;
}

.navbar-nav li
{
    padding-right: 25px;
}

.nav-link
{
    font-size: 1.1em !important;
    font-weight: bold;
}

.navbar-nav > .active > a { 
    background-color: violet;
    border-radius: 5px; 
}
<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.12.9/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<nav id="main-navbar" class="navbar navbar-expand-md navbar-dark sticky-top">
            <div class="container-fluid"> <!--100% of the screen-->
                <a id="logo" href="#top">
                    <img src="Images/logo.svg" alt="Website logo">
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarResponsive">
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <a class="nav-link text-light" href="#about">About</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-light" href="#portfolio">Portfolio</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-light" href="#contact">Contact</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
0
tsahib 3 Сен 2020 в 14:12

2 ответа

Лучший ответ

Исправьте код следующим образом:

1) Удалите курс 'text-light' из тега. Так должно быть

<a class="nav-link" href="#about">About</a>

2) Добавьте data-spy="scroll" к элементу, который следует использовать в качестве прокручиваемой области (часто это элемент <body>).

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

3) Обновите селектор CSS:

.navbar-nav .active {
    background-color: violet;
    border-radius: 5px;
}
body {
    position: relative;
}
.navbar {
    padding: 0.8rem;
    background-color: #1C2331;
}
.navbar-nav li {
    padding-right: 25px;
}
.nav-link {
    font-size: 1.1em !important;
    font-weight: bold;
}
.navbar-nav .active {
    background-color: violet;
    border-radius: 5px;
}
<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.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<body data-spy="scroll" data-target=".navbar" data-offset="0">
<nav id="main-navbar" class="navbar navbar-expand-md navbar-dark sticky-top">
  <div class="container-fluid">
    <!--100% of the screen-->
    <a id="logo" href="#top"> <img src="Images/logo.svg" alt="Website logo"> </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item"> <a class="nav-link" href="#about">About</a> </li>
        <li class="nav-item"> <a class="nav-link" href="#portfolio">Portfolio</a> </li>
        <li class="nav-item"> <a class="nav-link" href="#contact">Contact</a> </li>
      </ul>
    </div>
  </div>
</nav>
<div id="about" class="container-fluid bg-success" style="padding-top:70px;padding-bottom:70px">
  <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>
  <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>
  <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>
  <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 id="portfolio" class="container-fluid bg-warning" style="padding-top:70px;padding-bottom:70px">
  <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>
  <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>
  <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>
  <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 id="contact" class="container-fluid bg-secondary" style="padding-top:70px;padding-bottom:70px">
  <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>
  <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>
  <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>
  <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>
0
Priya jain 4 Сен 2020 в 11:00

Удалите курс 'text-light' из тега <a>

Добавьте data-spy="scroll" к элементу, который следует использовать в качестве прокручиваемой области (часто это элемент <body>).

Затем добавьте атрибут data-target со значением идентификатора или именем класса панели навигации (.navbar). Это необходимо для того, чтобы убедиться, что панель навигации связана с прокручиваемой областью.

Обратите внимание, что прокручиваемые элементы должны соответствовать идентификатору ссылок внутри элементов списка навигационной панели (<div id="section1"> соответствует <a href="#section1">).

Требуется относительное позиционирование. Для правильной работы элемента с data-spy="scroll" требуется свойство CSS position со значением "relative".

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style>
body {
    position: relative;
}
.navbar {
    padding: 0.8rem;
    background-color: #1C2331;
}
.navbar-nav li {
    padding-right: 25px;
}
.nav-link {
    font-size: 1.1em !important;
    font-weight: bold;
}
.navbar-nav > .active > a {
    background-color: violet;
    border-radius: 5px;
}
</style>
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
  <ul class="navbar-nav">
    <li class="nav-item"> <a class="nav-link" href="#section1">Section 1</a> </li>
    <li class="nav-item"> <a class="nav-link" href="#section2">Section 2</a> </li>
    <li class="nav-item"> <a class="nav-link" href="#section3">Section 3</a> </li>
    <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> Section 4 </a>
      <div class="dropdown-menu"> <a class="dropdown-item" href="#section41">Link 1</a> <a class="dropdown-item" href="#section42">Link 2</a> </div>
    </li>
  </ul>
</nav>
<div id="section1" class="container-fluid bg-success" style="padding-top:70px;padding-bottom:70px">
  <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 id="section2" class="container-fluid bg-warning" style="padding-top:70px;padding-bottom:70px">
  <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 id="section3" class="container-fluid bg-secondary" style="padding-top:70px;padding-bottom:70px">
  <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>
<div id="section41" class="container-fluid bg-danger" style="padding-top:70px;padding-bottom:70px">
  <h1>Section 4 Submenu 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 id="section42" class="container-fluid bg-info" style="padding-top:70px;padding-bottom:70px">
  <h1>Section 4 Submenu 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>
</body>
</html>
0
Priya jain 4 Сен 2020 в 10:42