jef*_*eff 367 html forms label input
我想知道以下两个代码片段之间的区别是什么:
<label>Input here : </label>
<input type='text' name='theinput' id='theinput'/>
Run Code Online (Sandbox Code Playgroud)
和
<label for='theinput'>Input here : </label>
<input type='text' name='theinput' id='theinput'/>
Run Code Online (Sandbox Code Playgroud)
我确定当你使用一个特殊的JavaScript库时它会有所作为,但除此之外,它是否验证HTML或其他原因需要?
Bar*_*mar 549
该<label>
标签可让您单击标签,它会像单击相关的输入元素上进行处理.有两种方法可以创建此关联:
一种方法是将label元素包装在input元素周围:
<label>Input here:
<input type='text' name='theinput' id='theinput'>
</label>
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用该for
属性,为其提供相关输入的ID:
<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>
Run Code Online (Sandbox Code Playgroud)
这对于使用复选框和按钮特别有用,因为这意味着您可以通过单击相关文本来检查框,而不必单击框本身.
在MDN中阅读有关此元素的更多信息.
Juk*_*ela 47
该for
属性将标签与控件元素相关联,如label
HTML 4.01规范中的描述中所定义.除其他事项外,这意味着当label
元素获得焦点时(例如通过单击),它会将焦点传递给其关联的控件.标签和控件之间的关联也可以由基于语音的用户代理使用,这可以在处理控件时向用户提供询问相关标签是什么的方式.(该关联可能不像在视觉渲染中那么明显.)
在问题的第一个例子中(没有for
),label
标记的使用没有逻辑或功能含义 - 它是无用的,除非你用CSS或JavaScript做一些事情.
HTML规范并不强制要求将标签与控件相关联,但Web内容可访问性指南(WCAG)2.0也是如此.这在技术文档H44中描述:使用标签元素将文本标签与表单控件相关联,这也解释了隐式关联(通过嵌套例如input
内部label
)不像显式关联via for
和id
attributes 那样得到广泛支持,
小智 14
简而言之它的作用是指id
输入,这就是全部:
<label for="the-id-of-the-input">Input here:</label>
<input type="text" name="the-name-of-input" id="the-id-of-the-input">
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
169733 次 |
最近记录: |