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

后端 未结 1 570

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条回答
  •  猫巷女王i
    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;
    }
    
    
    Content
    Content
    Content

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