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

背景を複数の選択肢からランダムで表示する

$
0
0

完成物

See the Pen random-background by ririli (@ririli) on CodePen.

ちょっと解説

するまでもないですが。

事前に背景の選択肢をarrayで定義しておきます。
今回は色にしましたが画像とかでもOK。

letbackgroundImageData=['red','blue','green']

ランダム要素のためにMath.random()の値を返す関数を定義します。
ポイントは0~maxまでの整数を返すようにすること。

functiongetRandInt(max){returnMath.floor(Math.random()*Math.floor(max));}

window.onloadのタイミングでrand関数を呼び出します。
その結果を定義した選択肢のarrayに適用。

window.onload=function(){constrandNum=getRandInt(backgroundImageData.length)constbackground=document.getElementById("background")background.style.backgroundColor=backgroundImageData[randNum]};

あとがき

こんな単純なことでも以外と要件にあったりするので誰かに役に立てば。
こうしておくと後任の担当者にも変更箇所が簡潔に見えて良さそう。


Viewing all articles
Browse latest Browse all 8670

Trending Articles