如何创建带有可点击标签的HTML复选框 [英] How to create an HTML checkbox with a clickable label

查看:168
本文介绍了如何创建带有可点击标签的HTML复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create an HTML checkbox with a label that is clickable (this means that clicking on the label turns the checkbox on/off)?

推荐答案

方法1:包装标签标签



将复选框包含在标签 / p>

Method 1: Wrap Label Tag

Wrap the checkbox within a label tag:

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


$ b

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

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



说明



't提到它,一个标签可以包括多达1个输入,并省略属性的,并且它将被假定为其中的输入。

Explanation

Since the other answers don't mention it, a label can include up to 1 input and omit the for attribute, and it will be assumed that it is for the input within it.

摘自 w3.org < a>(我强调):

Excerpt from w3.org (with my emphasis):


[for attribute]明确地将定义的标签与另一个控件相关联。如果存在,此属性的值必须与同一文档中某个其他控件的id属性的值相同。 缺少时,要定义的标签与元素的内容相关联。

要将标签与其他控件间接关联,元素必须在LABEL元素的内容中。在这种情况下,LABEL只能包含一个控制元素。标签本身可能位于关联控件之前或之后。

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.

使用此方法比


  • 不需要分配 id

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

不需要在< label>

输入的可点击区域也是标签的可点击区域,因此没有两个单独的位置可以控制复选框 - 只要一个,不管< input> 和实际的标签文本有多远,无论你应用什么样的CSS。

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 /

Demo with some CSS: http://jsfiddle.net/qYZFJ/

这篇关于如何创建带有可点击标签的HTML复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆