滚动时动态更改背景颜色 [英] dynamically change background color on scroll

查看:362
本文介绍了滚动时动态更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在滚动时动态更改背景颜色?

Is there any way to change background color dynamically on scroll?

例如,请参阅此网站( https://www.samsung.com/sec/smartphones/galaxy-note9/

For example, refer this site(https://www.samsung.com/sec/smartphones/galaxy-note9/)

首次访问该网站时,背景颜色为蓝色。

When you first access that site, background color is blue.

向下滚动时,颜色变为黑色。

While scroll down, it's color change to black smoothly.

另见本网站( codepen.io/Funsella/pen/yLfAG /

第二个网站与第一个网站相同。但它的颜色立即变了。

Second site is same with first. But it's color changed at once.

但第一个网站的颜色不会立刻改变。

But first site's color is not change at once.

它逐渐变化与滚动位置相关。

It changed gradually related to scroll position.

body {
  height: 100vh;
}
.section1 {
  background-color: white;
  height: 100%;
}
.section2 {
  background: linear-gradient(#f05fa6, #ed1654);
  height: 100%;
}

<html>
<body>
  <section class="section1">
    SECTION1
  </section>
  <section class="section2">
    SECTION2
  </section>
</body>
</html>

上面的代码是我正在处理的。

Above code is what I'm worked on.

当前它的颜色被每个部分分开。

Current it's color is split by each section.

当我向下滚动时,我想改变颜色背景颜色:白色 - > 背景:线性渐变(#f05fa6,#ed1654)

When I scroll down, I want to change color background-color: white -> background: linear-gradient(#f05fa6, #ed1654)

对此有什么解决方案吗?

Is there any solution about this?

谢谢。

推荐答案

您需要通过考虑页面的滚动偏移量来平滑地插入颜色( window.scrollY window.pageYOffset

You need to smoothly interpolate the colors by taking into account the page's scroll offset (window.scrollY, or window.pageYOffset on older browsers).

三星网站正在转换纯色而不是渐变,这有点简单。

The Samsung site is transitioning a solid color instead of a gradient, which is a bit simpler.

赞这(参见CodePen ):

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})`
})

您可以对渐变颜色应用相同的逻辑。

You can apply the same logic to the gradient colors.

这篇关于滚动时动态更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆