滚动时动态改变背景颜色

17
有没有办法在滚动时动态更改背景颜色?
例如,参考此网站(https://www.samsung.com/sec/smartphones/galaxy-note9/)。
当您首次访问该网站时,背景颜色是蓝色的。
向下滚动时,它会平稳地变成黑色。
还可以查看此网站(codepen.io/Funsella/pen/yLfAG/)。
第二个网站与第一个相同。但它的颜色一次性改变。
但第一个网站的颜色不会一次性改变。
它会根据滚动位置逐渐改变。

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>

上述代码是我正在处理的内容。

目前,它的颜色是由每个部分分开的。

当我向下滚动时,我想要更改颜色 background-color: white -> background: linear-gradient(#f05fa6, #ed1654)

这方面有什么解决方案吗?

5个回答

21

您需要通过考虑页面的滚动偏移量(window.scrollY或旧浏览器上的window.pageYOffset)来平滑插值颜色。

三星网站正在转换为纯色而不是渐变,这样会更简单一些。

像这样(查看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})`
})

你可以将相同的逻辑应用于渐变颜色。


1
完美运行。在这一行中,为什么要加上 1 并除以 150 - Hide
如果你不使用 1 +,那么颜色就不会从 rgb(69, 111, 225) 开始,而是在页面顶部变成纯白色。如果你算一下,就会明白为什么了。150 只是我随意选择的一个常数,可以根据需要调整,以控制颜色过渡的速度。 - atomiks
我明白了。但是在Safari上不起作用。所以我添加了 section1.style.webkitBackgroundColorsection1.style.mozBackgroundColor。但还是不行。我应该使用哪个属性? - Hide
哪个Safari?我发布的代码是ES2015,适用于从2015年末左右发布的浏览器。如果您正在使用渐变,则应使用style.background而不是style.backgroundColor - atomiks
我访问了您提供的网站,但它无法正常工作。我使用的是OSX(iMac 2017)系统,Chrome浏览器可以正常运行。 - Hide
显示剩余8条评论

4
我认为您需要使用CSS的“transition”属性。
body {
  background: green;
  transition: 0.3s all;
}

然后,您可以添加、删除元素并更改颜色:
$(function() {
$(window).scroll(function () {
   if ($(this).scrollTop() > 50) {
      $(‘body’).addClass(‘colorChange’)
      $(‘header’).addClass(‘displayNone’)
      $(‘nav’).removeClass(‘navBackgroundStart’)
      $(‘nav ul’).addClass(‘addBlackBackground’)
   } 
   if ($(this).scrollTop() < 50) {
      $(‘body’).removeClass(‘colorChange’)
      $(‘header’).removeClass(‘displayNone’)
      $(‘nav’).addClass(‘navBackgroundStart’)
      $(‘nav ul’).removeClass(‘addBlackBackground’)
   } 
});
});

或许CSS过渡是一次性改变的。但我想让它像第一个网站那样。 - Hide

4
我尝试使用atomiks的解决方案,但自定义结束颜色太困难了。我发现了更好的解决方案,使用chroma.js
您需要使用两种或更多颜色生成比例尺:
var scale = chroma.scale(['#1abc9c', '#e74c3c']).domain([0, $(document).height()]);
$(window).on('scroll', function () {
    $('.section').css('background-color', scale(window.pageYOffset));
});

这里我创建了一个比例尺,并设置所需颜色,然后添加自定义域名,以便我的比例尺可以使用偏移位置,该位置可以从0(页面顶部)到3600(页面底部)。或者,您可以通过一些数学运算来获取介于0和1之间的滚动位置值。

然后,当我们滚动时,我们可以使用当前滚动位置的比例尺。它将在到达页面底部的最后一个颜色#e74c3c之前,在我们的两个颜色之间生成RGBA颜色。


这个可以运行。Chroma.js可以计算两种颜色/位置之间所有可能的颜色值。根据上面的答案,您将元素的颜色设置为每个滚动位置chroma给出的颜色。 - Tom

2
这段jQuery代码可以改变网页背景色。
$(document).ready(function() {
    var scroll_pos = 0;
    $(document).scroll(function() {
        scroll_pos = $(this).scrollTop();
        if(scroll_pos > 300) {
            $("body").css('background-color', 'blue');
        } else {
            $("body").css('background-color', 'red');
        }
    });
});

不要忘记添加过渡CSS,以获得您在示例中看到的效果。
body {
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

使你的部分类别的背景透明。
.section1, section2 {
  background-color: transparent;
}

不是我想要的。它变成了第二个网站的样子。但我想要像第一个网站那样改变颜色。 - Hide

0

这个效果可以通过一点JavaScript实现

首先创建一个带有内容的div。创建一个比内容小的框,并将溢出属性设置为滚动。

使用少量的JavaScript添加功能。首先创建一个事件监听器,当使用滚动效果时触发函数。当该事件监听器触发时,动态地将背景颜色设置为您的要求。

document.getElementById("myDIV").addEventListener("scroll", myFunction);

function myFunction() {
  document.getElementById("myDIV").style.backgroundColor = "red";
}
div {
  border: 1px solid black;
  width: 400px;
  height: 400px;
  overflow: scroll;
  transition: all 0.5s ease;
}
<p>Try the scrollbar in the div</p>
<div id="myDIV">Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
<br><br>
Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</div>


这个并不处理滚动位置,只是一次性的“在滚动时,永远将其变为红色”的逻辑。 - ggorlen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接