JS:div枠の色をスライダーで変化させる

JavaScript

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script src="main.js"></script>
	<title>スライダー応用2</title>
	<style>
		#box{
			margin: 0 auto;
			border: solid 1px #555;
			width: 90%;
			height: 100px;
		}
	</style>
</head>
<body>
	<div id="box"></div>
	<p>
		<input id="slider" type="range" min="0" max="255" value="128" step="1">
		<span id="sliderValue"></span>
	</p>
</body>
</html>

main.js

// スライダー応用2
let slider = null;
let sliderValue = null;
let box = null;

function setBGColor(){
	const color = `rgb(0, ${slider.value}, 0)`;
	console.log(color);

	box.style.backgroundColor = color;
}

// 起動時の処理
window.addEventListener("load", ()=>{
	// スライダー、スライダー値DOM取得
	slider = document.getElementById("slider");
	sliderValue = document.getElementById("sliderValue");
	box = document.getElementById("box");

	// スライドさせたときの処理
	slider.addEventListener("input", setBGColor);

	// スライダー初期状態を反映
	setBGColor();
});

コメント