2012/03/27

HTML5 JavaScript カラー

HTML5のスライダーを使って、バックグラウンドの色をRGBで制御するスクリプトを作ってみた。

JavaScript部分のソースはこんな感じ。
<script type="text/javascript">
<!--
function setColor() {
   obj = document.getElementsByClassName('change');      
   for (var i = 0;i < obj.length; i++) {
      obj[i].addEventListener
      ('change', function(){changeColor()}, false);
      }
        changeColor();
      }

function changeColor() {
   var red = document.frmColor.red.value;
   var green = document.frmColor.green.value;
   var blue = document.frmColor.blue.value;
   var redStr;
   var greenStr;
   var blueStr;
 
   red = parseInt(red);
   green = parseInt(green);
   blue = parseInt(blue);
   document.body.style.backgroundColor = 
     "rgb(" +  red +","+ green +","+ blue + ")";

   if(red < 16){ 
      redStr = "0"+ red.toString(16);
   }else{
      redStr = red.toString(16);
   }
   if(green <16){
      greenStr ="0"+green.toString(16);
   }else{
      greenStr = green.toString(16);
   }
   if(blue <16){
      blueStr ="0"+blue.toString(16);
   }else{
      blueStr = blue.toString(16);
   }
   document.frmColor.colorNum.value = 
        "#" +  redStr + greenStr + blueStr;
   document.frmColor.redNum.value = red;
   document.frmColor.greenNum.value = green;
   document.frmColor.blueNum.value = blue;
   }
window.onload = setColor;
//-->
</script>
続いてHTMLのフォームの部分。
<form name="frmColor" onload="setColor()" >
<label for="red">R </label>
<input type="range" name="red" class = 
"change" min="0" max="255" value="203">
<input type="text"  size="3"  name="redNum"  value="203" >
<br />
<label for="green">G </label>
<input type="range" name="green" class = 
"change" min="0" max="255" value="244">
<input type="text"  size="3"  name="greenNum"  value="244">
<br />
<label for="blue">B </label>
<input type="range" name="blue" class = 
"change" min="0" max="255" value="156">
<input type="text"  size="3"  name="blueNum" value="156">
<br />
<input type="text" name="colorNum">
</form>