对具有 span 元素的键盘的辅助功能支持

Accessibility support for keyboard with span element

我有一些元素可以单击并用作按钮。但是,屏幕阅读器看不到它们。为了纠正这个问题,我正在尝试添加一个函数,该函数将向任何角色设置为按钮的元素添加此类支持。

<span role="button">clickable</span>

我写了这个 jQuery 函数,但它不太管用。

$(document).on("keypress", "[role='button']", function(e) {
    var code = e.which;
    // 13 = Return, 32 = Space
    if ((code === 13) || (code === 32)) {
        $(this).click();
    });
}

我错过了什么?

<span>s 通常无法聚焦;没有焦点,它不会捕获按键。

您可以在上面加上 tabindex,正如 MDN button role page 中讨论的那样。

在设计可访问性时,尤其是在使用非标准 UX 元素作为 UX 输入时,tabindex 变得非常重要……而且非常烦人。

为什么不直接使用 <button> - 您可以将它们设置为看起来像 <span> 的样式,并从所有本机功能中受益。

我可能错过了某个浏览器可能需要的样式,因为它是我脑海中浮现出来的,但你明白了。

重要 - 下面向您展示了如何 'reset' a <button> - 请不要在生产中使用它,除非在按钮和按钮之间添加一些区别周围文字。

html{
   font-size: 1em;
}
.like-span{
  background: none; /*essential*/
 border: none; /*essential*/
 padding: 0; /*essential*/
 font: inherit; /*important as otherwise the text will look slightly different*/
  color: inherit; /*if you want the span the same colour as the rest of the sentence*/
 cursor: pointer; /*make sure you add this, but if you really want it to behave like a span you would leave this out*/
 outline: inherit; /*I would not recommend this as it removes focus indicator, but is fine as part of a reset if you are adding your own style */
}
.blue{
    color: blue;
}
<p>This is a sentence with a <button class="like-span">button</button> that looks just like a span</p>
<p class="blue">This is a sentence with a <button class="like-span">button</button> that looks just like a span</p>