Изменение цвета фона при прокрутке - PullRequest
0 голосов
/ 19 мая 2019

, поэтому я попытался написать собственную версию кода, чтобы изменить цвет фона страницы при прокрутке.Я искал по всему Интернету, но я просто продолжаю находить примеры Jquery и никаких ванильных JS, которые действительно показывают мне, как это сделать.

Моими первыми мыслями были обработка цветов и анимации в css и запуск их в JS.Если бы я хотел обрабатывать анимацию в CSS, это путь, нет?Во всяком случае, мой код явно не работает, так что кто-нибудь сможет мне помочь?

Это, вероятно, не так эффективно, как следовало бы, поэтому любые советы там также будут полезны.

Я еще не закончил анимационную часть в css, но основы заложены.Поэтому моя идея состояла в том, чтобы выбрать все разные цвета, а затем поместить их в массив.Затем сделайте цикл внутри функции.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css\style.css">
    <title>Site experiment</title>
</head>
<body>

<section>
<h1 id="first-h1">This site is an experiment on scroll effects</h1>
</section>

<section>
<h1 id="second-h1">I really hope this helps me learn vanilla JavaScript better</h1>
</section>

<section>
<h1 id="third-h1">I think it will honestly</h1>
</section>

<section>
<h1 id="fourth-h1">Or maybe it will frustrate me till the end of time</h1>
</section>

<section>
<h1 id="fifth-h1">Even if that does happen, I'll still keep trying</h1>
</section>

</body>
<script src="js\app.js"></script>
</html>

@import url('https://fonts.googleapis.com/css?family=Roboto+Mono');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto Mono', monospace;
}

body {
    background-color: #E5E1EE;
    transition: 0.3s all;
}

section {
    height: 100vh;
}

h1 {
    margin: 15rem;
}

.lightCyan {
    background-color: #DFFDFF;
}

.darkSkyBlue {
    background-color: #90BEDE;
}

.aquamarine {
    background-color: #68EDC6;
}

.electricBlue {
    background-color: #90F3FF;
}

    let bdy = document.querySelector('body');
let cyan = bdy.classList.add('lightCyan');
let skyBlue = bdy.classList.add('darkSkyBlue');
let aqua = bdy.classList.add('aquamarine');
let electric = bdy.classList.add('electricBlue');
let colors = [cyan, skyBlue, aqua, electric];


window.addEventListener('scroll', function () {
    if (document.documentElement.scrollTop || document.body.scrollTop > window.innerHeight) {
        for(let i = 0; i < colors.length; i++) {
           colors.push(i);
        }
    }
})

Ответы [ 2 ]

1 голос
/ 19 мая 2019

Если вы хотите изменить цвет фона, когда данный раздел попадает в верхнюю часть экрана, вы можете попробовать что-то вроде:

const colors = ['', 'lightCyan', 'darkSkyBlue', 'aquamarine', 'electricBlue']

const sections = [...document.getElementsByTagName('section')]

window.addEventListener('scroll', function () {

  const scrollFromTop = window.pageYOffset

  for (let i = 0; sections.length > i; i++) {

    if (scrollFromTop <= sections[i].offsetTop) {
      document.body.className = colors[i] 
      break
    } 

  }

})
@import url('https://fonts.googleapis.com/css?family=Roboto+Mono');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Roboto Mono', monospace;
}

body {
  background-color: #E5E1EE;
  transition: 0.3s all;
}

section {
  height: 100vh;
}

h1 {
  margin: 15rem;
}

.lightCyan {
  background-color: #DFFDFF;
}

.darkSkyBlue {
  background-color: #90BEDE;
}

.aquamarine {
  background-color: #68EDC6;
}

.electricBlue {
  background-color: #90F3FF;
}
<section>
<h1 id="first-h1">This site is an experiment on scroll effects</h1>
</section>

<section>
<h1 id="second-h1">I really hope this helps me learn vanilla JavaScript better</h1>
</section>

<section>
<h1 id="third-h1">I think it will honestly</h1>
</section>

<section>
<h1 id="fourth-h1">Or maybe it will frustrate me till the end of time</h1>
</section>

<section>
<h1 id="fifth-h1">Even if that does happen, I'll still keep trying</h1>
</section>
0 голосов
/ 19 мая 2019

Вы можете просто использовать тривиальный массив цветов.

let bdy = document.querySelector('body');
let colors = ['lightgreen', 'tomato', 'orange', 'purple'];

window.addEventListener('scroll', function () {
    if (document.documentElement.scrollTop || window.pageYOffset > window.innerHeight) {
    var diff = parseInt(window.pageYOffset - window.innerHeight);
    var step = parseInt(window.innerHeight*2);
    bdy.style.backgroundColor = colors[Math.floor(diff/step)];
    }
})
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto Mono', monospace;
}

body {
    background-color: #E5E1EE;
    transition: 0.3s all;
}

section {
    height: 100vh;
}

h1 {
    margin: 15rem;
}

.lightCyan {
    background-color: #DFFDFF;
}

.darkSkyBlue {
    background-color: #90BEDE;
}

.aquamarine {
    background-color: #68EDC6;
}

.electricBlue {
    background-color: #90F3FF;
}
<section>
<h1 id="first-h1">This site is an experiment on scroll effects</h1>
</section>

<section>
<h1 id="second-h1">I really hope this helps me learn vanilla JavaScript better</h1>
</section>

<section>
<h1 id="third-h1">I think it will honestly</h1>
</section>

<section>
<h1 id="fourth-h1">Or maybe it will frustrate me till the end of time</h1>
</section>

<section>
<h1 id="fifth-h1">Even if that does happen, I'll still keep trying</h1>
</section>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...