JavaScript滚动更改背景颜色

时间:2020-09-15 05:16:32

标签: javascript html css background-color

我正在练习Javascript和CSS。向下滚动时,我想更改背景颜色。我不想为此使用库。我已经按照这个code-pen演示来学习逻辑,但是他使用了jquery。我遵循了w3school的scrollTop。我的JavaScript逻辑可以正常工作,但不能像demo这样工作。我想我必须针对每个div才能更改背景颜色,但是不知道如何。

function showScrollColorChange() {
  //let scroll = window.scrollTop() + (window.height() / 3); 

  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 30) {
    document.body.classList.add('color-violet')
  } if (document.body.scrollTop > 40 || document.documentElement.scrollTop > 40) {
    document.body.classList.add('color-green')
  } else {
    document.body.classList.add('color-orange')
  }
}

/* document.body.addEventListener('scroll', () => {
  showScrollColorChange()
}) */
window.onscroll = function () { showScrollColorChange() };
*{
  box-sizing: border-box;
}

body{
  margin: 0;
  padding: 0;
  transition: background 300ms linear, color 300ms linear;
}

.container{
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 50px;
  min-height: 100vh;
}

p{
  width:50%;
  font-size: 20px;
}

img {
  width:500px;
  height: 500px;
  border-radius: 5px;
}
/* colours */
.color-violet {
  background-color: #7A4EAB;
}
.color-indigo {
  background-color: #4332CF;
}
.color-blue {
  background-color: #2F8FED;
}
.color-green {
  background-color: #4DCF42;
}
.color-yellow {
  background-color: #FAEB33;
}
.color-orange {
  background-color: #F19031;
}
.color-red {
  background-color: #F2293A;
}
<div class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>

3 个答案:

答案 0 :(得分:1)

这是一种动态的方式。

获取所有容器元素并将其顶部位置添加到数组中:

containers = document.getElementsByClassName("container");
var containertops = [];
containertops.push(0);  // add for space before 1st container
for (var i = 0; i < containers.length; i++) {
  containertops.push(containers[i].offsetTop);
}

按使用顺序排列颜色类别的数组。更改颜色和顺序很容易:

// array of colours to use
var colours = [
  "white",
  "color-violet",
  "color-indigo",
  "color-blue",
  "color-green",
  "color-yellow",
  "color-orange",
  "color-red",
];

在滚动功能中,循环遍历容器顶部位置的数组。对于循环中的每个i,使用它作为索引从colors数组中获取新颜色,以便每个容器的颜色都改变。如果容器多于颜色,请使用最后一种颜色。

// loop through the containers and add a new colour as the containers change
  for (var i = 0; i < containertops.length; i++) {

    // if this container is at the top of the screen get a new colour class
    if (document.body.scrollTop >= containertops[i] || document.documentElement.scrollTop >= containertops[i]) {
      document.body.className = '';  // clear class

      // if we have not enough colours, use the last colour class again
      colourclass= (i>=colours.length?colours.length-1: i);
      document.body.classList.add(colours[colourclass]);
    }
  }

这是起作用的代码:

//dynamically add all containers to array
containers = document.getElementsByClassName("container");
var containertops = [];
containertops.push(0);  // add for space before 1st container
for (var i = 0; i < containers.length; i++) {
  containertops.push(containers[i].offsetTop);
}

// array of colours to use
var colours = [
  "white",
  "color-violet",
  "color-indigo",
  "color-blue",
  "color-green",
  "color-yellow",
  "color-orange",
  "color-red",
];

function showScrollColorChange() {
  // loop through the containers and add a new colour as the containers change
  for (var i = 0; i < containertops.length; i++) {
  
     // if this container is at the top of the screen get a new colour class
    if (document.body.scrollTop >= containertops[i] || document.documentElement.scrollTop >= containertops[i]) {
    
      document.body.className = '';  // clear class      
     // if we have not enough colours, use the last colour class again
      colourclass= (i>=colours.length?colours.length-1: i);
      document.body.classList.add(colours[colourclass]);
    }
  }
}


window.onscroll = function() {
  showScrollColorChange()
};
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  transition: background 300ms linear, color 300ms linear;
}

.container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 50px;
  min-height: 100vh;
}

p {
  width: 50%;
  font-size: 20px;
}

img {
  width: 500px;
  height: 500px;
  border-radius: 5px;
}


/* colours */

.color-violet {
  background-color: #7A4EAB;
}

.color-indigo {
  background-color: #4332CF;
}

.color-blue {
  background-color: #2F8FED;
}

.color-green {
  background-color: #4DCF42;
}

.color-yellow {
  background-color: #FAEB33;
}

.color-orange {
  background-color: #F19031;
}

.color-red {
  background-color: #F2293A;
}
<div class="container">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
  <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
  <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
  <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
  <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
  <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>

答案 1 :(得分:0)

我看到2种解决方案:

  1. 您只需将类添加到您的正文中,所以随着时间的推移,正文将具有每个类,并且其颜色将被设置为最后一个类,因此您还应使用classList.remove('className');删除每个未使用的类。
  2. 只需使用document.body.style.background = '#FFFFFF'更改主体背景,并为每种更改的颜色添加注释,以免造成混淆。

答案 2 :(得分:0)

IntersectionObserver非常方便。您只是观察每个容器。

我已将名为_class的自定义属性添加到该元素。它保存了如果元素进入/离开视口应添加/删除的类的名称。

观察者从主线程运行,因此其性能更高。

要查看其工作原理,您需要全屏打开。将该阈值设置为0.9,这意味着在将类添加到正文之前,必须先看到90%的div。

let containers = document.querySelectorAll(".container")

let observer = new IntersectionObserver((entries) => {
   entries.forEach((entry, i) => {
      let color = entry.target.attributes._class.nodeValue;
      if(entry.isIntersecting) {
        document.body.className = "";
         document.body.classList.add(color);
      }
   })
}, {threshold: 0.9})

containers.forEach(container => {
   observer.observe(container);
})
*{
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

body{
  margin: 0;
  padding: 0;
  transition: background 300ms linear, color 300ms linear;
}

.container{
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 50px;
  min-height: 100vh;
}

p{
  width:50%;
  font-size: 20px;
}

img {
  width:500px;
  height: 500px;
  border-radius: 5px;
}
/* colours */
.color-violet {
  background-color: #7A4EAB;
}
.color-indigo {
  background-color: #4332CF;
}
.color-blue {
  background-color: #2F8FED;
}
.color-green {
  background-color: #4DCF42;
}
.color-yellow {
  background-color: #FAEB33;
}
.color-orange {
  background-color: #F19031;
}
.color-red {
  background-color: #F2293A;
}
<div _class="color-violet" class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div _class="color-indigo" class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div _class="color-blue" class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div _class="color-green" class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>
  <div _class="color-yellow" class="container">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
      sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
      <img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
  </div>