1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2020-03-11

完成物

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

ちょっと解説

するまでもないですが。

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


let backgroundImageData = [
    'red',
    'blue',
    'green'
]

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


function getRandInt(max) {
   return Math.floor(Math.random() * Math.floor(max));
}

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

window.onload= function() {
    const randNum = getRandInt(backgroundImageData.length)

    const background = document.getElementById("background")

    background.style.backgroundColor = backgroundImageData[randNum]
};

あとがき

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

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?