如何使我的自定义复选框可访问?

How do I make my custom checkbox accessible?

我正在尝试为我正在使用的网站实现更多的可访问性。我在按钮内有一个自定义复选框,后面是一个复选框列表。当我使用屏幕reader 时,我希望屏幕reader 能够在复选框为unmarked/marked 时告诉我。这适用于所有复选框,但我的按钮内的复选框除外。该按钮的用途是 mark/unmark 列表中的所有其他复选框(这是由 JavaScript 完成的)。一切正常,除了屏幕reader在我unmark/mark它时什么也没说。

这里是代码:

<button id="checkAll" class="btn btn-default checkAll checkAllInit" 
data-target="#everyCheckbox">
<span class="icon icm icm-checkbox_select" role="checkbox"></span>
<span class="text">Unmark all</span></button>

下面基本上是一个复选框列表,通过键盘导航和屏幕都可以访问和理解reader。只是按钮不会给出正确的反馈。

感谢任何建议。

无效html。您可以使用 https://validator.w3.org/nu/ to check your code. A <button> cannot have any interactive components nested in it. See https://www.w3.org/TR/html53/sec-forms.html#the-button-element

Content model: Phrasing content, but there must be no interactive content descendant.

这会混淆屏幕 reader。您需要一个简单的按钮或一个简单的复选框。

如果您没有使用原生 <input type='checkbox'>,那么您需要 role='checkbox' aria-checked。只需在 javascript 中切换 truefalse 之间的 aria-checked 值,屏幕 reader 将宣布更改。

首先是一个button element cannot contain any "interactive content",即没有其他表单控件,audio个元素,video个元素等

理想情况下,您应该使用原生 HTML 元素,即 form 元素环绕复选框和按钮,以及 input 元素及其 type set to checkbox. You'll also need to associate labels with the checkboxes. With these native elements, you don't need WAI-ARIA attributes such as role='checkbox' and aria-checked; these WAI-ARIA attibutes are actually redundant (see e.g. the article On HTML belts and ARIA braces 。 )

如果您有充分的理由使用 span、CSS 和 JavaScript 的组合来创建自定义复选框,您将需要额外的标记来使这些复选框易于访问:

  • tabindex="O" 以确保键盘用户可以触及复选框,
  • role='checkbox' 使屏幕阅读器能够弄清楚他们正在处理的元素类型,
  • aria-checked(值为 true 或 false)使屏幕阅读器能够识别复选框的状态,
  • aria-labelledbyassociate a "label" with the checkbox.

如您所见,如果您在 HTML 具有原生元素的地方使用自定义元素,您会为自己创造很多额外的工作。

请参阅此代码以更好地理解如何编写可访问的复选框。 请像这样定义复选框:

<h1>Show checkboxes:</h1>

<form action="/action_page.php">
  <input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
  <input type="checkbox" name="vehicle3" value="Boat" checked> I have a boat<br><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>
By using this method the checkboxes will be properly accessible by default and also, screen reader will announce the state.
If there are custom checkboxes which are to be made accessible, then please refer:
https://webdesign.tutsplus.com/tutorials/how-to-make-custom-accessible-checkboxes-and-radio-buttons--cms-32074