zoukankan      html  css  js  c++  java
  • html5中<label>标签的for属性使用方式方法详细分

    介绍的内容是html5中<label>标签的for属性使用方式方法详细分析。

    在freecodecamp上HTML教程的Create a Set of Radio Buttons这一节中,看到这样一段话,

    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.https:www.cqxftyyj.com

    大概的意思是:最好的做法,是给label标签,添加for属性,其值与input标签的id属性的值相同,以在label和input之间创建关联。

    同时,给出一段示例代码,如下:

    <!-- Code 1 -->
    <label for="indoor"> 
      <input id="indoor" type="radio" name="indoor-outdoor">Indoor 
    </label>

    代码中,label的for属性值与input的id属性值相同。从这段代码中,并不能看出关联在何处。

    关于label的for属性的定义如下:

    The for attribute specifies which form element a label is bound to.
    译文:for属性指定label与表单中的哪个元素进行绑定。

    示例代码:

    <!-- Code 2 -->
    <form action="/action_page.php">
      <input type="radio" name="gender" id="male" value="male">
      <label for="male">Male</label>
      <br>
      <input type="radio" name="gender" id="female" value="female">
      <label for="female">Female</label>
      <br>
      <input type="radio" name="gender" id="other" value="other">
      <label for="other">Other</label>
      <br>
      <input type="submit" value="Submit">
    </form>

    对比两段代码,不难发现,

    1. label与input标签的包含关系不同。Code 1 的label和input,属于包含关系,Code 2 的label和input相对独立。

    2. label与input在页面上的排列方式不同。通过Chrome的开发者工具不难发现,Code 1 的运行结果,label标签将input标签遮盖,Code 2 的运行结果,label标签与input标签并列。

    3. label与input一一对应。点击label的内容,对应的单端按钮都会被选中。

    如果,我们将两段代码中label的for属性删除,则之前的第1点和第2点不变,变化的是第3点。Code 1 的运营结果,点击label的内容,照旧能够选中单选按钮。而 Code 2 的则不同,点击label的内容,无法选中单选按钮。

    经过简单的代码运行结果对比,我们能够验证文章开头引用的那段话是正确的。为label添加for属性的这个做法,能够提高代码质量。

  • 相关阅读:
    手动创建分区以及软硬raid的问题
    实用小工具:VNC的安装
    安装使用xen虚拟化工具
    使用vsftp与shell实现对进程与服务状态的监控
    windows server2008下搭建ftp服务
    业界虚拟化技术分析
    Android命名规范(自定义)
    Android Paint和Color类
    Android 应用中十大常见 UX 错误
    漫谈互联网产品设计之人性的弱点,你躺枪了木有?
  • 原文地址:https://www.cnblogs.com/zqw111/p/12928940.html
Copyright © 2011-2022 走看看