简体   繁体   中英

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

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 of the webpage it is on (The website is one page only).

The only way i could think of doing this is adding onclick events to the links that go to the different sections of the page, however this would not allow me to change the colour of the header/navigation bar for when the user scrolls manually to a new section.

I was wondering if someone could point me in the right direction as I'm not sure where to start.

Here is the website as it stands now if people want to view it:

www.kylebinger.com

Here is my HTML markup regarding the header

<header>
    <div class="container">
        <nav>
            <a href="#home">Welcome</a>
            <a href="#featuredWork">Work</a>
            <a href="#caseStudy">Case Study</a>
            <a href="#about">About</a>
            <a href="#contact">Contact</a>
        </nav>
    </div>
</header>

Thanks in advance for any help.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM