简体   繁体   English

在网站的不同部分进行标题/导航更改颜色

[英]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. 我能想到这样做的唯一方法是将onclick事件添加到转到页面不同部分的链接,但是当用户手动滚动到a时,这不允许我更改标题/导航栏的颜色。新的部分。

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 www.kylebinger.com

Here is my HTML markup regarding the header 这是关于标题的HTML标记

<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. JQuery的offset和scrollTop函数应该可以解决问题。 .offset() gets the current coordinates of the element, while .scrollTop() will get the current scrollbar position. .offset()获取元素的当前坐标,而.scrollTop()将获取当前滚动条位置。 Compare them and change CSS when conditions are met. 比较它们并在满足条件时更改CSS。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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