是否有关于标签和输入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>
当前回答
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包含类似的内容时
label input {
vertical-align: bottom;
}
为了确保无线电的垂直对齐。
来自W3的HTML4规范:
标签本身可以放置在标签的前面、后面或周围 相关的控制。
<label for =“姓氏”>姓氏</label> <输入类型=“文本” id=“姓氏” />
or
<输入类型=“文本” id=“姓氏” /> <label for =“姓氏”>姓氏</label>
or
<标识> <input type="text" name="lastname" /> 姓 < / >标签
请注意,当表格用于布局时,标签在一个单元格中,其关联的表单字段在另一个单元格中,则不能使用第三种技术。
任何一个都是有效的。我喜欢使用第一个或第二个示例,因为它提供了更多的样式控制。
您需要考虑的一件事是复选框和无线电输入与javascript的交互。
使用下面的结构:
<label>
<input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
<span>Label text</span>
</label>
当用户点击“标签文本”时,controlCheckbox()函数将被触发一次。
但是,当输入标记被单击时,controlCheckbox()函数可能会在一些较老的浏览器中被触发两次。这是因为输入和标签标签都会触发附加到复选框的onclick事件。
然后您的checkboxState中可能会有一些错误。
我最近在IE11上遇到了这个问题。我不确定现代浏览器是否有这种结构的问题。
我非常喜欢将元素包装在<label>中,因为我不需要生成id。
我是一名Javascript开发人员,使用React或Angular生成可以被我或其他人重用的组件。然后很容易在页面中复制一个id,导致奇怪的行为。
有关W3的建议,请参阅http://www.w3.org/TR/html401/interact/forms.html#h-17.9。
他们说这两种方法都可以。他们将这两个方法描述为显式(使用“for”和元素的id)和隐式(将元素嵌入到标签中):
明确:
for属性显式地将一个标签与另一个控件关联:for属性的值必须与相关联的控件元素的id属性的值相同。
隐式:
若要隐式地将一个标签与另一个控件关联,该控件元素必须位于label元素的内容中。在这种情况下,LABEL可能只包含一个控制元素。