4
3

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.

【JavaScript】画像などをランダムに表示する方法

Last updated at Posted at 2016-09-08

JavaScriptで画像などをランダムに表示する方法についてです。
表示させる内容を日替わりなどで変化させたいことがありますね。

次のようなコードを<body>タグ内の表示したい場所に記述します。

<script type="text/javascript">
<!--

//赤字の箇所にランダムに表示したいものを列記します。(タグ可能。改行するのは不可)
//「' ',」で追加、最後のみカンマは不要。
var list = new Array(
'ランダム表示1',
'ランダム表示2',
'ランダム表示3'
);

var random_hyoji = Math.floor(list.length*Math.random());
document.write(list[random_hyoji]);

//-->
</script>

なお、上の方法だと直接HTMLに触れることになります。
ランダムに表示したいものを頻繁に変えるなら設定自体は別なファイルにしておいた方が楽でしょう。

その場合は、上の方法の最初の「<script type="text/javascript">」「<!--」と
最後の「//-->」「</script>」の行を削除し、JavaScriptファイルとして保存します。(例 ファイル名「random_hyoji.js」)

そして<body>タグ内の表示したい場所で次のように記述します。

<script type="text/javascript" src="random_hyoji.jsへのファイルパス"></script>
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?