【问题标题】:Dynamically change background color on scroll滚动时动态更改背景颜色
【发布时间】:2018-10-04 01:46:05
【问题描述】:

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

例如,参考这个网站(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)

有什么解决办法吗?

【问题讨论】:

    标签: javascript css dom-events


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 完美运行。在这一行,const y = 1 + (window.scrollY || window.pageYOffset) / 150,为什么要加上1和150分开?
    • 如果你不使用1 + ,那么颜色不会从rgb(69, 111, 225)开始,它会在页面顶部变为纯白色。如果你做数学,你会明白为什么。 150 只是我选择的一个随机数字 - 一个常数,可以根据您希望颜色转换的速度进行更改。
    • 我明白了。无论如何,它在 safari 上不起作用。所以我添加了section1.style.webkitBackgroundColor 和section1.style.mozBackgroundColor。但它不起作用。我应该使用什么属性?
    • 哪个 Safari?我发布的代码是 ES2015,它将在 2015 年末左右发布的浏览器上运行。如果您使用渐变,那么它是 style.background 而不是 style.backgroundColor。
    • 我访问了您链接的网站,但它不起作用。我也使用 OSX(iMac 2017)。 Chrome 工作正常。
    【解决方案2】:

    我认为你需要使用 CSS 的“过渡”属性。

    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 过渡会立即更改。但我想让它像第一个网站一样。
    【解决方案3】:

    我尝试使用具有自定义结束颜色的 atomiks 解决方案,但这太难了。通过使用chroma.js,我发现自己是一个更好的解决方案

    你需要用你的两种颜色(或更多)生成一个比例:

    var scale = chroma.scale(['#1abc9c', '#e74c3c']).domain([0, $(document).height()]);
    $(window).on('scroll', function () {
        $('.section').css('background-color', scale(window.pageYOffset));
    });
    

    在这里,我用我想要的颜色创建了一个scale,然后我添加了一个自定义域,以便我的比例可以使用从 0(页面顶部)到 3600(页面底部)的偏移位置。或者,您可以尝试通过一些数学运算获得介于 0 和 1 之间的滚动位置值。

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

    【讨论】:

    • 这是我来这里寻找的答案。感谢您的色度提示,顺便说一句;我想我最终会使用它。
    【解决方案4】:

    这个 jquery 代码改变了 body 的背景颜色。

    $(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;
    }
    

    【讨论】:

    • 跟我的目的不一样。它像第二个站点一样发生了变化。但我想像第一个网站一样改变颜色。
    【解决方案5】:

    这个效果可以用一点 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2014-04-05
      • 2021-01-01
      • 2017-04-23
      • 2020-04-20
      相关资源
      最近更新 更多