普段は PHP ばかり書いていますが、今日は要求があったので Javascript 書いてみました。気分的に jQuery は使いません。
以下の CSS を用意しておきます。
1 2 3 | .rand_item { display: none; } |
HTML に .rand_item と付加すればデフォルトで非表示になりますね。
要はこれを Javascript で表示に変更、class を変更してしまえば良いのですよ。
ちなみに、各項目には id で rand_01 と識別番号を付けておく必要がありますよ。
1 2 3 4 5 6 7 8 9 10 11 | <ul> <li id="rand_01" class="rand_item">テスト</li> <li id="rand_02" class="rand_item">テスト</li> <li id="rand_03" class="rand_item">テスト</li> <li id="rand_04" class="rand_item">テスト</li> <li id="rand_05" class="rand_item">テスト</li> <li id="rand_06" class="rand_item">テスト</li> <li id="rand_07" class="rand_item">テスト</li> <li id="rand_08" class="rand_item">テスト</li> <li id="rand_09" class="rand_item">テスト</li> </ul> |
それで以下が Javascript のコード。
ページを読み込むと自動的に起動して、ランダムに3個表示します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | window.onload=function() { var randnum = 0; var exist = new Array(); var count = 0; var run = 0; get_rand: while(run < 3) { randnum = 1+Math.floor(Math.random()*9); exist[count] = randnum; count++; for(var i = 0, n = exist.length; i < n-1; i++) { if(randnum == exist[i]) { continue get_rand; } } document.getElementById('rand_0' + randnum).className = 'rand_item_open'; run++; } } |
基本的にコードにコメント書くの好きじゃないのでごめんなさい。
こういうのは裏で function とかにしておいて、そこではコメント盛りだくさんってのが私の趣味というかやり方です。


Comments