Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8669

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

$
0
0

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

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

サンプルコード

HTML

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

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

CSS

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

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

javascript

exportdefaultclassbackgroundChange{constructor(elem){this.elem=elem;this.elemHeight=this.elem.clientHeight;this.percentage=Math.round(this.elemHeight/360);this.init();}init(){this.bindEvents();}bindEvents(){constbh=window.innerHeight;window.addEventListener('load',()=>{this.setting(bh);});window.addEventListener('scroll',()=>{this.setting(bh);});}setting(bh){constoffsetY=window.pageYOffset;constscrollBottom=bh+offsetY;constcalc=Math.floor(scrollBottom/this.percentage);this.changeBackground(calc);}changeBackground(calc){this.elem.style.backgroundColor=`hsl(${calc}, 100%, 50%)`;}}constelem=document.querySelector('[data-module="backgroundChange"]')newbackgroundChange(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(){constbh=window.innerHeight;window.addEventListener('load',()=>{this.setting(bh);});window.addEventListener('scroll',()=>{this.setting(bh);});}

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

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

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

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

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

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


Viewing all articles
Browse latest Browse all 8669

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>