ランダム色の生成

以下の3つの方法でランダム色を生成できます。

16677216*Math.random() を使う ・・・→

色指定の #RRGGBB 形式を使う  ・・・→

色指定の rgb関数 を使う  ・・・→

Sample Source......................................................................>>>

<script language="JavaScript"><!--
  var timer = null;         //タイマー変数
  function Select(n){
     if(timer != null)clearInterval(timer);
     if(n==1){
           timer = setInterval("Color1()",1000);   //方法1の場合
     }else if(n==2){
           timer = setInterval("Color2()",1000);   //方法2の場合
     }else if(n==3){
           timer = setInterval("Color3()",1000);   //方法3の場合
     }else{       //停止ボタン
           dv1.style.backgroundColor = "";
           dv2.style.backgroundColor = "";
           dv3.style.backgroundColor = "";
     }
  }
  function Color1(){
       dv1.style.backgroundColor = 16677216*Math.random();
  }
  function Color2(){
       c = RandomColor();
       dv2.style.backgroundColor = "#" + c;
  }
  function RandomColor(){
       var c = new String(); //文字列オブジェクト"c"を定義
       for(i=0;i<3;i++){
           c1 = Math.floor(Math.random()*255); //0〜254の乱数を生成
           c2 = c1.toString(16); //16進数に変換
           if(c2.length<2)c2 = "0" + c2; //1桁の場合は0を付ける
           c = c + c2; //色指定の RRGGBB 形式を生成
        }
        return c;
  }
  function Color3(){
       var r = Math.floor(Math.random()*255); //0〜254の乱数を生成
       var g = Math.floor(Math.random()*255);
       var b = Math.floor(Math.random()*255);
       var rgb = "rgb(" + r + "," + g + "," + b + ")";
       dv3.style.backgroundColor = rgb;
  }

// -->
</script>
</head>

<body>
<div id="dv1" style="position:absolute; left:300px; top:70px; width:200px; height:30px;border:thin solid"></div>
<div id="dv2" style="position:absolute; left:300px; top:110px; width:200px; height:30px;border:thin solid"></div>
<div id="dv3" style="position:absolute; left:300px; top:150px; width:200px; height:30px;border:thin solid"></div>

<p>以下の3つの方法でランダム色を生成できます。</p>
<form name="form1" >
  <p>16677216*Math.random() を使う
          <input type="button" name="bt1" value="方法1" onclick="Select(1)"> ・・・→
  </p>
  <p>色指定の #RRGGBB 形式を使う
          <input type="button" name="bt2" value="方法2" onclick="Select(2)"> ・・・→
  </p>
  <p>色指定の rgb関数 を使う
          <input type="button" name="bt2" value="方法3" onclick="Select(3)"> ・・・→
  </p>
  <p>
          <input type="button" name="bt3" value="停止" onclick="Select(4)">
  </p>
</form>  


(最終更新:12/12/21)
フレーム構成になっています・・・<[ホーム] >> [HTML整理ノート]>