是否有关于标签和输入HTML元素嵌套的最佳实践?
经典的方式:
<label for="myinput">My Text</label>
<input type="text" id="myinput" />
or
<label for="myinput">My Text
<input type="text" id="myinput" />
</label>
是否有关于标签和输入HTML元素嵌套的最佳实践?
经典的方式:
<label for="myinput">My Text</label>
<input type="text" id="myinput" />
or
<label for="myinput">My Text
<input type="text" id="myinput" />
</label>
当前回答
将输入嵌套到标签中有几个优点,特别是带有单选/复选框字段时,
.unchecked,支票{显示:没有;} 标签输入:not(:checked) ~ .unchecked{display:inline;} 标签输入:checked ~ .checked{display:inline;} <标识> <input type="checkbox" value="something" name="my_checkbox"/> . <span class="unchecked">Not Checked</span> <span class="checked">Is checked </span> . < / >标签
正如你从演示中看到的,在输入字段之前嵌套其他元素允许,
要单击以激活字段的文本 输入字段后面的元素将根据字段的状态动态设置样式。
此外,HTML std允许多个标签与一个输入字段相关联,但这会使屏幕阅读器感到困惑,解决这个问题的一种方法是将输入字段和其他元素嵌套在一个标签元素中。
其他回答
来自W3的HTML4规范:
标签本身可以放置在标签的前面、后面或周围 相关的控制。
<label for =“姓氏”>姓氏</label> <输入类型=“文本” id=“姓氏” />
or
<输入类型=“文本” id=“姓氏” /> <label for =“姓氏”>姓氏</label>
or
<标识> <input type="text" name="lastname" /> 姓 < / >标签
请注意,当表格用于布局时,标签在一个单元格中,其关联的表单字段在另一个单元格中,则不能使用第三种技术。
任何一个都是有效的。我喜欢使用第一个或第二个示例,因为它提供了更多的样式控制。
如果在label标签中包含input标签,则不需要使用'for'属性。
也就是说,我不喜欢在标签中包含input标签,因为我认为它们是独立的,不包含实体。
As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).
因为W3C和主要浏览器供应商的决定(允许“任何你喜欢的方式来做”,而不是“做正确的方式”),今天的网络是如此混乱,我们开发人员不得不处理如此复杂和多样化的遗留代码。
这两种方法都是正确的,但是将输入放在标签内会大大降低使用CSS进行样式化时的灵活性。
首先,<标签>限制了它可以包含的元素。例如,如果<input>不在<label>内,则只能在<input>和标签文本之间放置<div>。
其次,虽然有一些变通方法可以使样式更容易,比如用span包装内部标签文本,但有些样式将继承自父元素,这可能会使样式更复杂。
第三方编辑
根据我的理解,标签的html 5.2规范规定,标签内容模型是短语内容。这意味着只有内容模型为短语content <label>的标签才允许在</label>内。
内容模型必须包含的内容的规范描述 作为元素的子元素和子元素。 大多数被归类为措辞内容的元素只能 包含本身被归类为措辞内容的元素, 没有任何流内容。
您需要考虑的一件事是复选框和无线电输入与javascript的交互。
使用下面的结构:
<label>
<input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
<span>Label text</span>
</label>
当用户点击“标签文本”时,controlCheckbox()函数将被触发一次。
但是,当输入标记被单击时,controlCheckbox()函数可能会在一些较老的浏览器中被触发两次。这是因为输入和标签标签都会触发附加到复选框的onclick事件。
然后您的checkboxState中可能会有一些错误。
我最近在IE11上遇到了这个问题。我不确定现代浏览器是否有这种结构的问题。