在刷freeCodeCamp巩固基础时,遇到了以下一段关于label
中for
属性的使用,以前从没留意过,特此记录下。
It is considered best practice to set a for attribute on the label element, with a value that matches the value of the id attribute of the input element. This allows assistive technologies to create a linked relationship between the label and the child input element. For example:
<label for="indoor">
<input id="indoor" type="radio" name="indoor-outdoor">Indoor
</label>
以上代码很简单,就是实现一个单选框的功能。
label标签
我们首先来认识以下 label
的作用。
The HTML
简单地理解这句话,label
提供了页面元素的解释,这其中就包括了与 input
标签的绑定。
继续看 MDN 上关于 label
和 input
的解释。
Associating a
- The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screenreader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
- You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.
大致理解为 label
通过对 input
标签的绑定,增加了对表单属性的解释,也方便了触屏设备的交互,点击 label
上的内容,即选中了 input
标签。
绑定方法
- for属性绑定
<label for="peas">Do you like peas?</label>
<input type="checkbox" name="peas" id="peas">
- 内联(nest)绑定
<label>Do you like peas?
<input type="checkbox" name="peas">
</label>
参考
HTML label Tag(须科学上网)
MDN Label