LoginSignup
3
5

More than 3 years have passed since last update.

スクロール量に応じて背景の色を変えたい

Last updated at Posted at 2019-12-17

スクロール量に応じて背景の色を変える方法

デモページ
こんな風なのが作りたい人向けの記事です。

サンプルコード

HTML

<div class="hogehoge" data-module="backgroundChange">
  <!-- ページのコンテンツ -->
</div>

ページのコンテンツ要素をラッピングする要素を用意します。
なんならbodyでもいいです。

CSS

.hogehoge {
  width: 100%;
  height: 10000px;
  transition: background .4s ease-out;
}

CSSで要素の高さを指定します。
なんなら指定しなくても高さ持っていれば別にいいです。
大事なのはbackgroundtransitionを指定することです。

javascript

export default class backgroundChange {
  constructor(elem) {
    this.elem = elem;
    this.elemHeight = this.elem.clientHeight;
    this.percentage = Math.round(this.elemHeight / 360);
    this.init();
  }
  init() {
    this.bindEvents();
  }
  bindEvents() {
    const bh = window.innerHeight;
    window.addEventListener('load', () => {
      this.setting(bh);
    });

    window.addEventListener('scroll', () => {
      this.setting(bh);
    });
  }
  setting(bh) {
    const offsetY = window.pageYOffset;
    const scrollBottom = bh + offsetY;
    const calc = Math.floor(scrollBottom / this.percentage);
    this.changeBackground(calc);
  }
  changeBackground(calc) {
    this.elem.style.backgroundColor = `hsl(${calc}, 100%, 50%)`;
  }
}

const elem = document.querySelector('[data-module="backgroundChange"]')

new backgroundChange(elem)

これでOKです。

解説

もう少し詳しく解説すると

constructor(elem) {
  this.elem = elem;
  this.elemHeight = this.elem.clientHeight;
  this.percentage = Math.round(this.elemHeight / 360);
  this.init();
}

ここで、newするときに引数で指定した要素を受け取ります。
そして、その要素の高さを取得して、
さらにそれを360等分して、Math.round()で小数点以下を四捨五入します。

なぜ360等分しているか木になる方は、「HSLカラーチャート」でググってみてください。
円形のカラーチャートが出てくると思います。円、つまり360度。そういうことです。

init() {
  this.bindEvents();
}

そしてイベンドバインドの関数を叩きます。

bindEvents() {
  const bh = window.innerHeight;
  window.addEventListener('load', () => {
    this.setting(bh);
  });

  window.addEventListener('scroll', () => {
    this.setting(bh);
  });
}

window.innerHeightでブラウザの高さを取得します。
そして、ページロード時とスクロール時に、背景の色を変える準備用の関数を叩きます。
その時に引数で、ブラウザの高さを渡します。

setting(bh) {
  const offsetY = window.pageYOffset; //垂直方向のスクロール量
  const scrollBottom = bh + offsetY; //ブラウザの高さ + 垂直方向のスクロール量
  const calc = Math.floor(scrollBottom / this.percentage); //ごにょごにょ計算してスクロールした割合出す
  this.changeBackground(calc);
}

ここがややこしいですが、ごにょごにょと計算して、
ページ全体のうちのどのくらいスクロールしたかを計算します。
そしてその計算した値を元に背景色を変える関数を叩きます。

changeBackground(calc) {
  this.elem.style.backgroundColor = `hsl(${calc}, 100%, 50%)`;
}

いよいよ、newする時に受け取った要素の背景色を替えます。
上でごにょごにょ計算した値をHSL形式の色指定の第一引数に突っ込みます。

これで、スクロールするたびに色が変わるようになっているはずです。

3
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5