将复选框与标签关联,如:
<input
id=“chx1”
type="checkbox">
<label
for=“chx1”
>STYLE LABEL LIKE A BUTTON</label>
复选框id与标签[for]同步。一旦单击一个按钮,它们就会关联起来
二者都
表现得像被点击了一样。在演示中,表单被包装在所有内容周围。通过将窗体作为公共父级引入,我们可以将窗体注册到事件(单击是公共的,但窗体、输入等具有特殊的事件)。我们将更改事件分配给表单,现在复选框可以在每次更改时做出反应,而不绑定到事件侦听器。在演示中评论了详细信息。
// Reference the form
const form = document.forms.Health;
// Register the form to change event
form.onchange = testSync;
// Pass Event Object (e)
function testSync(e) {
// Reference the checked checkbox
const checked = e.target;
// Get it's #id
let ID = e.target.id;
// Get the button/label associated with checkbox
let button = document.querySelector(`[for=${ID}]`);
// if the checkbox is checked...
if (checked.checked) {
// Set the button/label text to checkbox ID
button.textContent = ID;
} else {
// Otherwise set text to the button/label .class
button.textContent = button.className;
}
return false;
}
label {
width: 50px;
border: 1px solid #cacaca;
border-radius: 3px;
font-size: 12px;
font-family: arial, helvetica, sans-serif;
padding: 10px 10px 10px 10px;
text-align: center;
display: inline-block;
text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3);
font-weight: bold;
color: #000;
background-color: #E6E6E6;
background-image: linear-gradient(to bottom, #E6E6E6, #CCC);
}
label:hover {
border: 1px solid #b3b3b3;
background-color: #cdcdcd;
background-image: linear-gradient(to bottom, #cdcdcd, #b3b3b3);
cursor: pointer;
}
<form id='Health'>
<input id="Nutrition" name='health' type="checkbox" value='H1'> Health 1<br>
<input id="Activity" name='health' type="checkbox" value='H2'> Health 2<br>
<input id="Medical" name='health' type="checkbox" value='H3'> Health 3<br>
<label class='Health1' for="Nutrition">Health1</label><br>
<label class='Health2' for="Activity">Health2</label><br>
<label class='Health3' for="Medical">Health3</label><br>
</form>