在网站的不同部分进行标题/导航更改颜色 [英] Make Header/Navigation change colour when on different section of the website

查看:67
本文介绍了在网站的不同部分进行标题/导航更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的个人投资组合网站重新设计网站。我有一个很酷的功能,我的标题/导航栏会根据网页的哪个部分改变颜色(网站只有一页)。

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).

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

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

这是关于标题的HTML标记

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>

提前感谢您的帮助。

推荐答案

JQuery的offset和scrollTop函数应该可以解决问题。 .offset()获取元素的当前坐标,而。scrollTop()将获得当前滚动条位置。比较它们并在满足条件时更改CSS。参见示例:

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>

这篇关于在网站的不同部分进行标题/导航更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆