单选表单中 <label> 的语义用法

Dig*_*nja 4 html forms semantic-markup radio-button

根据HTML5 Doctor 的说法

标签代表用户界面中的标题。标题可以与特定的表单控件(称为标签元素的带标签控件)相关联,可以使用 for 属性,也可以将表单控件放在标签元素本身内。

因此,将其放入带有单选按钮的上下文中。在一个要求您在表单中选择最喜欢的水果的示例中,如果我说标签“Apple”是其<label>单选按钮,为了使标签可点击,我会将单选控件放在里面,例如:

<label>
   <input type="radio" name="fruit" value="apple"/> Apple
</label>
Run Code Online (Sandbox Code Playgroud)

由于<label>示例中的元素也显示为整个输入值的标签,因此这显示了我的问题“您最喜欢的水果?” 进入标签,从而使整个部分充满标签?

<label>Your favourite fruit?</label>
<label>
    <input type="radio" name="fruit" value="apple"/> Apple
</label>
<label>
    <input type="radio" name="fruit" value="banana"/> Banana
</label>
<label>
    <input type="radio" name="fruit" value="watermelon"/> Watermelon
</label>
Run Code Online (Sandbox Code Playgroud)

那是对的吗?

然后,在他们的示例中,for第一个<label>包含问题的属性也指的是id元素的 。但我不能这样做,因为我有 3 个元素,所以这意味着我不可能使用该for属性?

Lee*_*ski 8

解决这个问题的语义方法是将单选按钮与 fieldset 元素分组。

<fieldset>
    <legend>Your favourite fruit?</legend>
    <label>
        <input type="radio" name="fruit" value="apple"/> Apple
    </label>
    <label>
        <input type="radio" name="fruit" value="banana"/> Banana
    </label>
    <label>
        <input type="radio" name="fruit" value="watermelon"/> Watermelon
    </label>
</fieldset>
Run Code Online (Sandbox Code Playgroud)

W3C 的辅助功能教程推荐使用这种方法来处理您的场景: https: //www.w3.org/WAI/tutorials/forms/grouping/和 MDN 的 Fieldset 文章: https: //developer.mozilla.org/en-US/文档/Web/HTML/元素/字段集

可以使用 CSS 改进字段集的默认呈现。一个例子在这里https://design-system.service.gov.uk/components/radios/