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

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

问题描述

如何创建带有可单击标签的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:包装标签标签

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

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

方法2:使用for属性

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

Method 2: Use the for Attribute

Use the for attribute (match the checkbox id):

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

注意:ID在页面上必须是唯一的!

NOTE: ID must be unique on the page!

由于其他答案均未提及,因此标签最多可以包含1个输入并省略for属性,并且将假定它是其中的输入.

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 (我的重点):

[for属性]显式地将要定义的标签与另一个控件相关联.如果存在,则此属性的值必须与同一文档中某些其他控件的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.

使用此方法相对于for有一些优点:

Using this method has some advantages over for:

  • 无需为每个复选框分配一个id(很棒!).

无需在<label>中使用多余的属性.

No need to use the extra attribute in the <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的演示:

Demo with some CSS:

label {
 border:1px solid #ccc;
 padding:10px;
 margin:0 0 10px;
 display:block; 
}

label:hover {
 background:#eee;
 cursor:pointer;
}

<label><input type="checkbox" />Option 1</label>
<label><input type="checkbox" />Option 2</label>
<label><input type="checkbox" />Option 3</label>

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

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