トグルスイッチは、ユーザーがオン/オフの2つの状態を切り替えることができるUIコンポーネントです。
トグルスイッチ
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript トグルスイッチ</title>
<link rel="stylesheet" href="./main.css" />
</head>
<body>
<div class="toggle-switch-container">
<div class="toggle-switch">
<input type="checkbox" id="toggle_switch" />
<label for="toggle_switch" class="switch"></label>
</div>
<span id="switch_status" class="switch-status">OFF</span>
</div>
<script src="./main.js"></script>
</body>
</html>
// ページの読み込みが完了
document.addEventListener("DOMContentLoaded", function () {
const toggleSwitch = document.getElementById("toggle_switch");
const switchStatus = document.getElementById("switch_status");
// トグルスイッチの状態を切り替える
toggleSwitch.addEventListener("change", function () {
if (this.checked) {
switchStatus.textContent = "ON";
console.log("スイッチはONです");
} else {
switchStatus.textContent = "OFF";
console.log("スイッチはOFFです");
}
});
});
.toggle-switch-container {
display: flex;
align-items: center;
font-family: Arial, sans-serif;
}
.toggle-switch {
position: relative;
width: 60px;
height: 34px;
margin-right: 10px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.switch {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: 0.4s;
border-radius: 34px;
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.2), 0 0 15px rgba(0, 0, 0, 0.1);
}
.switch:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: 0.4s;
border-radius: 50%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
input:checked + .switch {
background-color: #2196f3;
}
input:checked + .switch:before {
transform: translateX(26px);
}
.switch-status {
font-size: 18px;
font-weight: bold;
color: #333;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}
出力結果