HTML <label> 标签
定义和用法
<label> 标签为 input 元素定义标注(标记)。
label 元素不会向用户呈现任何特殊效果。不过,它为鼠标用户改进了可用性。如果您在 label 元素内点击文本,就会触发此控件。就是说,当用户选择该标签时,浏览器就会自动将焦点转到和标签相关的表单控件上。
<label> 标签的 for 属性应当与相关元素的 id 属性相同。
提示:<label> 的 for 属性必须等于相关元素的 id 属性才能将它们绑定在一起。也可以通过将元素放置在 <label> 元素内将标签绑定到元素。
<label> 标签可为多个元素定义标签(标记):
<input type="checkbox"><input type="color"><input type="date"><input type="datetime-local"><input type="email"><input type="file"><input type="month"><input type="number"><input type="password"><input type="radio"><input type="range"><input type="search"><input type="tel"><input type="text"><input type="time"><input type="url"><input type="week"><meter><progress><select><textarea>
使用上述元素与 label 的正确方式将有益于以下用户:
- 屏幕阅读器用户(当用户聚焦在元素上时,将朗读标签)
- 难以点击非常小的区域(例如复选框)的用户 - 因为当用户单击
<label>元素中的文本时,它会切换输入(这增加了点击区域)
实例
三个带有 label 的单选按钮:
<form action="/action_page.php"> <input type="radio" id="html" name="fav_language" value="HTML"> <label for="html">HTML</label><br> <input type="radio" id="css" name="fav_language" value="CSS"> <label for="css">CSS</label><br> <input type="radio" id="javascript" name="fav_language" value="JavaScript"> <label for="javascript">JavaScript</label><br><br> <input type="submit" value="提交"> </form>
属性
| 属性 | 值 | 描述 |
|---|---|---|
| for | 元素 id | 规定 label 绑定到哪个表单元素。 |
| form | 表单 id | 规定 label 字段所属的表单。 |
全局属性
<label> 标签还支持 HTML 中的全局属性。
事件属性
<label> 标签还支持 HTML 中的事件属性。
默认的 CSS 设置
大多数浏览器将使用以下默认值显示 <label> 元素:
label {
cursor: default;
}
浏览器支持
| Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Opera |
| 支持 | 支持 | 支持 | 支持 | 支持 |