CSS在滚动时更改固定标题的背景颜色

4
有没有 CSS-only 的技术可以在用户滚动页面时更改固定菜单栏的背景颜色?
例如,颜色从 silver 变为 gold: https://codepen.io/dpilafian/pen/pwREjR 以下是我目前正在使用的 JavaScript 解决方案:
HTML
<body>
   <header>
      <nav>Navigation Bar</nav>
   </header>
   <main>
      <h1>The Main Event</h1>
      <h2>Scroll this page up.</h2>
      <p>Content goes here.</p>
   </main>
   <footer>
      Footer
   </footer>
</body>

CSS(LESS)

body {
   padding-top: 30px;
   >header, >footer {
      background-color: silver;
      }
   }
body >header {
   position: fixed;
   top: 0px;
   width: 100%;
   transition: all 3s;
   &.scrolled {
      background-color: gold;
      }
   }

JavaScript(使用jQuery)

const elem = $('body >header');
const scrolled = () => {
   const threshold = $(document).scrollTop() > 50;
   elem.toggleClass('scrolled', threshold);
   };
$(window).on({ scroll: scrolled });

如果可能的话,用某种CSS视差解决方案替换上述JavaScript解决方案会更方便。

因为我很累,需要喝茶,并且不久后还要遛狗,所以我不会很快弄清楚这个问题。但是,我们可以尝试使用 position: sticky; 来进行一些“有效的滚动检测”,据我所知这是CSS中唯一可用的方法。我之后会再回来处理这个问题。 - Fred Gandt
说到许多事情,我完全支持使用 CSS 而不是 JavaScript,但在这种情况下,我认为 JavaScript 是处理事件的方法。您可能想根据页面信息执行许多不同的操作。这与视觉差有什么关系? - sheriffderek
@sheriffderek CSS视差效果不会被JavaScript事件触发。 - Dem Pilafian
CSS视差效果不会被JavaScript事件触发 - 我不确定这是一个陈述还是一个答案。我不理解为什么它带有parallaxbackground-color标签。 - sheriffderek
3个回答

2

是否有一种纯CSS的技术,可以在用户向上滚动页面时更改固定菜单栏的背景颜色?

没有。使用CSS无法基于滚动位置更改规则。


2
你可以使用一些技巧,放置一个透明的绝对定位的div,并估计所需的滚动距离转换为top坐标。当你滚动到它并悬停在上面时,这将触发背景变化。
这只是一个通用示例,但你可以调整坐标和大小以符合自己的需要(可悬停的div仅用于视觉参考)。

body {
  font-family: sans-serif;
  margin: 0px;
  padding-top: 30px;
}

body header,
body footer {
  text-align: center;
  background-color: silver;
  padding: 10px;
}

body header {
  position: fixed;
  top: 0px;
  width: 100%;
  transition: all 3s;
}

.scrolled {
  background-color: gold;
}

.hoverEffect {
  position: absolute;
  height: 200px;
  background: transparent;
  border: 1px solid lightgray;
  text-align: center;
  line-height: 200px;
  top: 432px;
  left: 0px;
  right: 0px;
}

.hoverEffect:hover+header {
  background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hoverEffect">scroll/hover to this part</div>
<header>
  <nav>Navigation Bar</nav>
</header>
<main>
  <h1>The Main Event</h1>
  <h2>Scroll this page up.</h2>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
  <p>Content goes here.</p>
</main>
<footer>
  Footer
</footer>


2

您可以利用bootstrap的affix和affix-top,它们根据您的滚动在affix和affix-top类之间切换。因此,您可以根据需要为.affix和.affix-top类提供css样式。

注意:当用户没有滚动或滚动回顶部时,会出现affix-top。


3
底层不就是 JavaScript 吗? - sheriffderek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接