Make Header/Navigation change colour when on different section of the website

后端 未结 1 568

I am working on a website redesign for my personal portfolio website. I had a cool feature in mind where my header/navigation bar would change colour depending on what section o

相关标签:
1条回答
  • 2021-02-06 18:24

    JQuery's offset and scrollTop functions should do the trick. .offset() gets the current coordinates of the element, while .scrollTop() will get the current scrollbar position. Compare them and change CSS when conditions are met. See example:

    var top1 = $('#home').offset().top;
    var top2 = $('#featuredWork').offset().top;
    var top3 = $('#caseStudy').offset().top;
    
    $(document).scroll(function() {
      var scrollPos = $(document).scrollTop();
      if (scrollPos >= top1 && scrollPos < top2) {
        $('#change').css('background-color', '#f00');
      } else if (scrollPos >= top2 && scrollPos < top3) {
        $('#change').css('background-color', '#0f0');
      } else if (scrollPos >= top3) {
        $('#change').css('background-color', '#00f');
      }
    });
    body {
      margin: 0;
      padding-top: 30px
    }
    header {
      position: fixed;
      top: 0;
      width: 100%;
      height: 30px;
      background-color: #000;
    }
    section {
      height: 500px;
      background-color: #aaa;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <header id="change">
      <div class="container">
        <nav>
          <a href="#home">Welcome</a>
          <a href="#featuredWork">Work</a>
          <a href="#caseStudy">Case Study</a>
        </nav>
      </div>
    </header>
    
    <section id="home">Content</section>
    <section id="featuredWork">Content</section>
    <section id="caseStudy">Content</section>

    0 讨论(0)
提交回复
热议问题