JavaScript addEventListenerでチェックボックスの背景色を変えるサンプル
環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.119
構文
1.チェックボックス要素の取得
const 変数名 = document.getElementById(セレクター名);
2.イベントリスナの追加
変数名.addEventListener(“click",function(e){処理コード
3.チェックボックスのチェック判定
if(変数名.checked)
使用例
<!DOCTYPE html>
<html>
<body>
<style>
/*背景css*/
#cft {
width: 120px;
height: 50px;
background: green;
}
</style>
<div id="cft">
<label><input type="checkbox" id="city"/>東京</label>
</div>
<script>
//チェックボックス要素「city」の取得
const city = document.getElementById("city");
// div要素「cft」の取得
const cft = document.getElementById("cft");
//イベントリスナの追加
city.addEventListener("click",function(e){
//チェックされたら
if(city.checked) {
cft.style.background = "yellow";
} else { //チェックされない
cft.style.background ="skyblue";
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<style>
/*背景css*/
#cft {
width: 120px;
height: 50px;
background: green;
}
</style>
<div id="cft">
<label><input type="checkbox" id="city"/>東京</label>
</div>
<script>
//チェックボックス要素「city」の取得
const city = document.getElementById("city");
// div要素「cft」の取得
const cft = document.getElementById("cft");
//イベントリスナの追加
city.addEventListener("click",function(e){
//チェックされたら
if(city.checked) {
cft.style.background = "yellow";
} else { //チェックされない
cft.style.background ="skyblue";
}
});
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <style> /*背景css*/ #cft { width: 120px; height: 50px; background: green; } </style> <div id="cft"> <label><input type="checkbox" id="city"/>東京</label> </div> <script> //チェックボックス要素「city」の取得 const city = document.getElementById("city"); // div要素「cft」の取得 const cft = document.getElementById("cft"); //イベントリスナの追加 city.addEventListener("click",function(e){ //チェックされたら if(city.checked) { cft.style.background = "yellow"; } else { //チェックされない cft.style.background ="skyblue"; } }); </script> </body> </html>
結果
初期背景色がgreenです。チェックボックスを入れたら「yellow」が表示されます。
チェックボックスを外したら背景色が「skyblue」で表示されます。