如何在没有字段集的情况下对表单输入进行分组?

时间:2018-01-15 15:14:28

标签: html forms accessibility wai-aria web-accessibility

问题:对表单元素进行分组

我有一个HTML表单,在很少的地方,一个控件由几个输入组成。一个例子是一组单选按钮。

我想明确地对这些输入及其标签进行分组,以便屏幕阅读器(除了通过将它们对齐在一条直线上的视觉表示之外)能够理解和宣布这种关系。

例如,我们说我有这样的控件:

<div class="control">
  <div class="control-label">Type</div>
  <div class="control-inputs">
    <input type="radio"
           name="type"
           value="a"
           id="type-a" />
    <label for="type-a">A</label>

    <input type="radio"
           name="type"
           value="b"
           id="type-b" />
    <label for="type-b">B</label>
  </div>
</div>

标准解决方案问题:Fieldset样式问题

fieldset元素和它的孩子legend似乎完全是为了这个(在下面的例子中使用)。

问题在于fieldsetlegend元素不能像普通元素(some discussion about it)那样设置风格,而现在除了Firefox以外,它们无法对齐使用我的布局所需的Flexbox将它们放在一行上。

<fieldset class="control">
  <legend class="control-label">Type</legend>
  <div class="form-inputs">
    <input type="radio"
           name="type"
           value="a"
           id="type-a" />
    <label for="type-a">A</label>

    <input type="radio"
           name="type"
           value="b"
           id="type-b" />
    <label for="type-b">B</label>
  </div>
</fieldset>

问题:还有其他方法吗?

这让我想知道除了使用fieldset元素之外,是否有一些可访问的方法可以对多个表单控件进行分组?

可能的解决方案:role="group"

有一个"group" role(在下面的示例中使用),可以添加到一个简单的div中,看起来它可以完成这项工作,但没有明确说明它是功能等同于使用字段集。如果确实如此,那么如何将该组的元素标记为legend的等效元素?

<div role="group"
     class="control">
  <div class="control-label">Type</div>
  <div class="control-inputs">
    <input type="radio"
           name="type"
           value="a"
           id="type-a" />
    <label for="type-a">A</label>

    <input type="radio"
           name="type"
           value="b"
           id="type-b" />
    <label for="type-b">B</label>
  </div>
</div>

2 个答案:

答案 0 :(得分:6)

基本上你已经在“可能的解决方案”部分回答了你的问题(顺便说一句,作为一个盲人,我对你用标题设置问题的方式印象深刻!)。你遗漏了一个小而简单的东西,aria-label属性:

<div role="group" class="control" aria-label="Type">

注意:这在屏幕上是不可见的,它只是一个屏幕阅读器解决方案。但是,如果要使其可见,请使用aria-labelledby属性执行以下操作:

<div role="group" class="control" aria-labelledby="pseudolegend">
<div id="pseudolegend" class="style-it-like-a-legend">Type</div>
[...]
</div>

pseudolegend可能是span甚至是p,当然,如果您认为它更合适。 我做的一个快速而肮脏的本地测试表明,至少对于JAWS和Chrome,fieldsetdivaria-label之间没有区别。

答案 1 :(得分:4)

注意:对于单选按钮组,您可以使用role=radiogroup。此外,为了向屏幕阅读器用户表达groupradiogroup的语义,需要accessible name作为分组元素。