我在堆栈中找到了这个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)更改为白色。 非常感谢您的帮助。
答案 0 :(得分: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>