不使用jQuery滚动功能突出显示活动链接

时间:2018-06-20 08:18:16

标签: javascript jquery bootstrap-4 scrollspy

我是jQuery的新手,正在使用Bootstrap scrollspy。 我可以使用jQuery滚动功能更改导航栏背景和导航链接的颜色,但活动链接被禁用。

$(document).ready(function() {
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll > 150) {
      $('#demo').css({
        'background-color': 'black',
        'transition': '0.5s'
      });
      $('.nav-link').css('color', 'white');
    } else {
      $('#demo').css({
        'background-color': 'white',
        'transition': '0.5s'
      });
      $('.nav-link').css('color', 'black');
    }
  });
});
.navbar-nav .nav-item .nav-link.active {
  color: red;
}
<html>

<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
  <style>
    .navbar-nav .nav-item .nav-link.active {
      color: red;
    }
  </style>
</head>

<body data-spy="scroll" data-target="#navbar-bkg" data-offset="0">
  <div class="container-fluid fixed-top" id="demo">
    <div class="container">
      <nav class="navbar navbar-expand-lg navbar-light" id="navbar-bkg">

        <div>
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="#first" id="home">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#second" id="about">About</a>
            </li>
          </ul>
        </div>
      </nav>
    </div>
    <!--Container ends-->
  </div>
  <div class="content" style="height: 400px" id="first"> </div>
  <div class="content" style="height: 600px; background-color: lightblue" id="second"> </div>

0 个答案:

没有答案