问题

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



解决方法

Method 1: Wrap Label Tag

Wrap the checkbox within a label tag:

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

Method 2: Use the for Attribute

使用 属性(匹配 id ):

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

Explanation

由于其他答案没有提及,一个标签可以包含最多1个输入,并省略属性的,并假设它是用于其中的输入. p>

摘自 w3.org (我强调):

[The for attribute] explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents.

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

使用此方法比 有一些优点:

  • No need to assign an id to every checkbox (great!).

  • No need to use the extra attribute in the <label>.

  • The input's clickable area is also the label's clickable area, so there aren't two separate places to click that can control the checkbox - only one, no matter how far apart the <input> and actual label text are, and no matter what kind of CSS you apply to it.

使用一些CSS演示: http://jsfiddle.net/qYZFJ/




相关问题推荐