Изменение цвета панели навигации Bootstrap4 при прокрутке в разных разделах веб-сайта

#javascript #html #jquery #css #bootstrap-4

#javascript #HTML #jquery ( jquery ) #css — код #начальная загрузка-4

Вопрос:

Я работаю над веб-сайтом, моим личным портфолио, с помощью bootstrap4, и у меня возникла хорошая идея, которая меняет цвет панели навигации на разных разделах моего веб-сайта.Я знаю, что мы используем функции смещения и прокрутки jQuery, и я пытался, но это не работало должным образом. Мне было интересно, может ли кто-нибудь указать мне правильное направление, как это сделать.

Вот код веб-сайта:

 <!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>
</head>
<body>

<header id="change">
<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">about</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section3">Contact</a>
      </li>    
    </ul>
  </div>  
</nav>
</header>

<div id="section1" class="container-fluid bg-success" style="padding-top:70px;height: 100vh;width:100%;">
  <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;height: 100vh;width:100%;">
  <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;heigth;height: 100vh;width:100%;">
  <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>


<script>

var top1 = $('#section1').offset().top;
var top2 = $('#section2').offset().top;
var top3 = $('#section3').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 amp;amp; scrollPos < top2) {
    $('#change').css('background-color', '#f00');
  } else if (scrollPos >= top2 amp;amp; scrollPos < top3) {
    $('#change').css('background-color', '#0f0');
  } else if (scrollPos >= top3) {
    $('#change').css('background-color', '#00f');
  }
});

</script>

</body>
</html> 

Заранее спасибо за помощь.

Ответ №1:

Цвет фона задается классом «bg-dark» на панели навигации. Поэтому я бы сделал это, удалив / добавив классы для цвета фона непосредственно на панели навигации. Для примера я создал несколько классов bg-color и присвоил панели навигации идентификатор. Могут быть более чистые решения, но я просто хочу привести здесь пример.

 .bg-purple {
  background-color: purple;
}

.bg-cyan {
  background-color: cyan;
}

.bg-orange {
  background-color: orange;
} 
 <!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>
</head>
<body>

<header id="change">
<nav id="navbar-change" class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">about</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section3">Contact</a>
      </li>    
    </ul>
  </div>  
</nav>
</header>

<div id="section1" class="container-fluid bg-success" style="padding-top:70px;height: 100vh;width:100%;">
  <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;height: 100vh;width:100%;">
  <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;heigth;height: 100vh;width:100%;">
  <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>


<script>

var top1 = $('#section1').offset().top;
var top2 = $('#section2').offset().top;
var top3 = $('#section3').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 amp;amp; scrollPos < top2) {
    $('#navbar-change').removeClass('bg-dark');
    $('#navbar-change').removeClass('bg-cyan');
    $('#navbar-change').removeClass('bg-orange');
    $('#navbar-change').addClass('bg-purple');
  } else if (scrollPos >= top2 amp;amp; scrollPos < top3) {
     $('#navbar-change').removeClass('bg-dark');
     $('#navbar-change').removeClass('bg-purple');
     $('#navbar-change').removeClass('bg-orange');
     $('#navbar-change').addClass('bg-cyan');
  } else if (scrollPos >= top3) {
     $('#navbar-change').removeClass('bg-dark');
     $('#navbar-change').removeClass('bg-purple');
     $('#navbar-change').removeClass('bg-cyan');
     $('#navbar-change').addClass('bg-orange');
  }
});

</script>

</body>
</html> 

Ответ №2:

Вам нужно добавить .navbar цвет фона, потому что background-color установлен в bg-dark классе with !important . Поэтому перезапишите !important свойство, которое вам нужно использовать cssText в качестве имени свойства, и все, что вы хотите добавить в css в качестве его значения.

 var top1 = $('#section1').offset().top;
var top2 = $('#section2').offset().top;
var top3 = $('#section3').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 amp;amp; scrollPos < top2) {
    $('#change .navbar').css("cssText", 'background:#f00!important');
  } else if (scrollPos >= top2 amp;amp; scrollPos < top3) {
    $('#change .navbar').css("cssText", 'background:#0f0!important');
  } else if (scrollPos >= top3) {
    $('#change .navbar').css("cssText", 'background:#00f!important');
  }
}); 
 <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>

<header id="change">
<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">about</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section3">Contact</a>
      </li>    
    </ul>
  </div>  
</nav>
</header>

<div id="section1" class="container-fluid bg-success" style="padding-top:70px;height: 100vh;width:100%;">
  <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;height: 100vh;width:100%;">
  <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;heigth;height: 100vh;width:100%;">
  <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>