【问题标题】:Dynamically change navbar color on scroll滚动时动态更改导航栏颜色
【发布时间】:2020-05-12 19:15:34
【问题描述】:

我在堆栈上找到了这个great solution

const [red, green, blue] = [69, 111, 225]
const section1 = document.querySelector('.section1')

window.addEventListener('scroll', () => {
  let y = 1 + (window.scrollY || window.pageYOffset) / 150
  y = y < 1 ? 1 : y // ensure y is always >= 1 (due to Safari's elastic scroll)
  const [r, g, b] = [red/y, green/y, blue/y].map(Math.round)
  section1.style.backgroundColor = rgb(${r}, ${g}, ${b})
})

但我想将颜色从 rgba(249, 82, 4, 1) 更改为白色。 非常感谢任何帮助。

【问题讨论】:

  • 你是想让它“变形”还是只是用淡入改变?
  • 只是慢慢地从橙色变为白色。谢谢!

标签: javascript scroll navbar addeventlistener


【解决方案1】:

稍微调整计算,您可以得到类似的结果(我们现在不是减少 rgb 值并逐渐变黑,而是增加它们并因此逐渐变白):

const [red, green, blue] = [249, 82, 4];
const section1 = document.querySelector('.navbar');

window.addEventListener('scroll', () => {
  let y = 1 + (window.scrollY || window.pageYOffset);
  y = y < 1 ? 1 : y;
  const [r, g, b] = [red + y, green + y, blue + y].map(Math.round);
  section1.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
})
body {
  height: 100vh;
  margin: 0;
  padding: 0;
}
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgb(249, 82, 4);
  height: 50px;
  width: 100%;
  transition: background-color 200ms ease;
}
.section {
  background: rgb(249, 82, 4);
  height: 300%;
 
}
<html>
<body>
  <section class="navbar">
  </section>
  <section class="section">
  </section>
</body>
</html>

【讨论】:

  • 太好了!谢谢!
猜你喜欢
  • 2014-07-05
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 2022-01-04
  • 2021-05-06
  • 2017-04-30
相关资源
最近更新 更多