HTML中label标签的使用

在刷freeCodeCamp巩固基础时,遇到了以下一段关于labelfor属性的使用,以前从没留意过,特此记录下。

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 上关于 labelinput 的解释。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值