JSを使ってカラーシミュレーターを作ってみよう。
[実行例]
上部に色とカラーコード、下部にrgb成分を設定するスライダーが表示されている。
スライダーを設定すると色とカラーコードが表示される。
[作例]
●index.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>title</title> <style> #box{ height:50px; border:1px solid #000; width:200px; font-size:30px; line-height:50px; } </style> </head> <body> <h1 id="box">#ffffff</h1> <p> R:<input type="range" min="0" max="255" class="param" value="255"><span>255</span><br> G:<input type="range" min="0" max="255" class="param" value="255"><span>255</span><br> B:<input type="range" min="0" max="255" class="param" value="255"><span>255</span><br> </p> <script> 'use strict'; window.onload=function(){ const box=document.getElementById("box"); const params=document.getElementsByClassName("param"); for(let i=0;i<params.length;i++){ params[i].addEventListener("input",function(){ let r=parseInt(params[0].value); let g=parseInt(params[1].value); let b=parseInt(params[2].value); let cCode="#"+hex(r)+hex(g)+hex(b); if(r+b+g<380){ box.style.color="white"; }else{ box.style.color="black"; } box.style.backgroundColor=cCode; box.textContent=cCode; this.nextElementSibling.textContent=this.value; }); } }; function hex(num){ let hex=num.toString(16); if(num<16){ hex='0'+hex; } return hex; } </script> </body> </html>
コメント