rgbColor.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RGBそれぞれを乱数で決定して背景色に設定</title>
<style>
input[type="button"]{
width: 200px;
}
</style>
<script>
window.addEventListener("load", function(){
let bd = document.getElementById("bd");
// 乱数で色名を作成
let btnRed = document.getElementById("btnRed");
let r, g, b;
// 赤ボタン
btnRed.addEventListener("click", function(){
r = Math.floor(Math.random() * 256);
g = 0;
b = 0;
let color = "rgb(" + r + "," + g + "," + b + ")";
bd.style.backgroundColor = color;
});
// 緑ボタン
btnGreen.addEventListener("click", function(){
r = 0;
g = Math.floor(Math.random() * 256);
b = 0;
let color = "rgb(" + r + "," + g + "," + b + ")";
bd.style.backgroundColor = color;
});
// 青ボタン
btnBlue.addEventListener("click", function(){
r = 0;
g = 0;
b = Math.floor(Math.random() * 256);
let color = "rgb(" + r + "," + g + "," + b + ")";
bd.style.backgroundColor = color;
});
});
</script>
</head>
<body id="bd">
<h1>RGBそれぞれを乱数で決定して背景色に設定</h1>
<p>
<input id="btnRed" type="button" value="red">
<input id="btnGreen" type="button" value="green">
<input id="btnBlue" type="button" value="blue">
</p>
</body>
</html>
実行イメージ
コメント