如何创建带有可点击标签的复选框?

如何创建带有可单击标签的 HTML 复选框(这意味着单击标签可以打开 / 关闭该复选框)?

答案

方法 1:包装标签标签

将复选框包装在label标签内:

<label><input type="checkbox" name="checkbox" value="value">Text</label>

方法 2:使用for属性

使用for属性(与复选框id匹配):

<input type="checkbox" name="checkbox" id="checkbox_id" value="value">
<label for="checkbox_id">Text</label>
<fieldset>
  <legend>What metasyntactic variables do you like?</legend>

  <input type="checkbox" name="foo" value="bar" id="foo_bar">
  <label for="foo_bar">Bar</label>

  <input type="checkbox" name="foo" value="baz" id="foo_baz">
  <label for="foo_baz">Baz</label>
</fieldset>
<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
    content: attr(value);
    margin: -3px 15px;
    vertical-align: top;
    white-space:nowrap;
    display: inline-block;
}
</style>
<label for="vehicle">Type of Vehicle:</label>
<input type="checkbox" id="vehicle" name="vehicle" value="Bike" />
<label for="myInputID">myLabel</label><input type="checkbox" id="myInputID" name="myInputID />
<form>
    <label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
    <label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>
<form>
  <label for="male">Male</label>
  <input type="radio" name="sex" id="male" />
  <br />
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" />
</form>
<label for="my_checkbox">Check me</label>
<input type="checkbox" name="my_checkbox" value="Car" />

使用label元素和for属性将其与复选框关联:

<label for="myCheckbox">Some checkbox</label> <input type="checkbox" id="myCheckbox" />

在带有复选框的角材料标签中

<mat-checkbox>Check me!</mat-checkbox>