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

rryofs0p  于 2023-04-01  发布在  其他
关注(0)|答案(3)|浏览(201)

是否有一种仅限CSS的技术,可以在用户向上滚动页面后更改固定菜单栏的背景颜色?
颜色从silver变为gold的示例:
https://codepen.io/dpilafian/pen/pwREjR
下面是我目前使用的JavaScript解决方案:

超文本标记语言

<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解决方案会很方便。

9udxz4iz

9udxz4iz1#

你可以使用bootstrap afix和affix-top,它可以根据你的滚动在afix和affix-top类之间切换。所以你可以根据你的需要给. afix和.affix-top类给予css。
注意:当用户没有滚动或它滚动回顶部时,会出现affix-top。

mspsb9vt

mspsb9vt2#

是否有一种仅限CSS的技术,可以在用户向上滚动页面后更改固定菜单栏的背景颜色?
不可以。CSS无法根据滚动位置更改规则。

axkjgtzd

axkjgtzd3#

你可以做一点小改动,放置一个透明的绝对位置div,并将滚动距离的估计值转换成top坐标,这样当你滚动到它并悬停它时,就会触发背景的变化。
这是一个通用的例子,但你可以调整坐标和大小来获得好处(hoverable 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>

相关问题