將默認文本標籤的 Checkbox 改為圖片風格(如圖片作為選項內容)。
<style>
.img-checkbox { display: none; }
.img-checkbox + label {
display: inline-block;
width: 48px; height: 48px;
background: url(off.png) no-repeat center;
cursor: pointer;
}
.img-checkbox:checked + label {
background-image: url(on.png);
}
</style>
<input type="checkbox" id="opt1" class="img-checkbox" />
<label for="opt1"></label>
點擊圖片即可切換選中狀態,語義清晰,無需 JS。
<img src="off.png" onclick="toggle(this)" />
<input type="hidden" name="opt" value="0" id="hiddenOpt" />
<script>
function toggle(img) {
var hidden = document.getElementById('hiddenOpt');
if (img.src.endsWith('off.png')) {
img.src = 'on.png'; hidden.value = '1';
} else {
img.src = 'off.png'; hidden.value = '0';
}
}
</script>
<input type="checkbox" name="recess" /> <img src="icon.png" alt="放假安排" />
圖片僅作裝飾,不參與交互邏輯。