在滚动时动态更改导航栏颜色

Dynamically change navbar color on scroll

我在堆栈中找到了这个

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) 更改为白色。 非常感谢任何帮助。

稍微调整一下计算,您可能会得到这样的结果(我们现在增加 rgb 值并逐渐变为白色,而不是减少 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>