gpt4 book ai didi

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

转载 作者:bug小助手 更新时间:2023-10-28 10:52:46 25 4
gpt4 key购买 nike

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

最佳答案

方法一:包装标签标签

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

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

方法二:使用for属性

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

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

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

说明

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

摘自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.

使用这种方法比for 有一些优势。 :

  • 无需分配 id到每个复选框(太棒了!)。

  • 无需使用<label> 中的额外属性.

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

带有一些 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>

关于html - 如何创建带有可点击标签的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6293588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com