Controle o foco com tabindex
Os elementos HTML padrão, como <button>
ou <input>
possuem acessibilidade de teclado integrada gratuitamente. No entanto, se você estiver construindo componentes interativos personalizados, use o tabindex
para garantir que eles sejam acessíveis pelo teclado.
Verifique se seus controles são acessíveis pelo teclado #
Uma ferramenta como o Lighthouse é ótima para detectar certos problemas de acessibilidade, mas algumas coisas só podem ser testadas por um ser humano.
Tente pressionar a Tab
para navegar pelo seu site. Você consegue acessar todos os controles interativos da página? Caso contrário, pode ser necessário usar tabindex
para melhorar a focalização desses controles.
Insira um elemento na ordem das guias #
Insira um elemento na ordem natural das guias usando tabindex="0"
. Por exemplo:
<div tabindex="0">Focus me with the TAB key</div>
Para focar um elemento, pressione a Tab
ou chame o método focus()
Remova um elemento da ordem de tabulação #
Remova um elemento usando tabindex="-1"
. Por exemplo:
<button tabindex="-1">Você não consegue me alcançar com a tecla TAB!</button>
Isso remove um elemento da ordem natural de tabulação, mas o elemento ainda pode ser focalizado chamando seu método focus()
Observe que aplicar tabindex="-1"
a um elemento não afeta os filhos dele; se eles estiverem na ordem das guias naturalmente ou por causa de um tabindex
, eles permanecerão na ordem das guias. Para remover um elemento e todos os seus filhos da ordem de tabulação, considere o uso o polyfill inert
WICG. O polyfill emula o comportamento de um inert
proposto, o que evita que os elementos sejam selecionados ou lidos por tecnologias assistivas.
Evite tabindex > 0
#
Qualquer tabindex
maior que 0 salta o elemento para a frente da ordem natural das guias. Se houver vários elementos com um tabindex
de tabulação maior que 0, a ordem das guias começa a partir do valor mais baixo maior que zero e segue seu caminho para cima.
Usar um tabindex
maior que 0 é considerado um antipadrão porque os leitores de tela navegam na página na ordem do DOM, não na ordem das guias. Se você precisar que um elemento venha antes da ordem de tabulação, ele deve ser movido para um ponto anterior no DOM.
O Lighthouse facilita a identificação de elementos com tabindex
> 0. Execute a Auditoria de Acessibilidade (Lighthouse > Opções > Acessibilidade) e procure os resultados da auditoria "Nenhum elemento tem um valor [tabindex] maior que 0".
Crie componentes acessíveis com "roving tabindex
" #
Se você estiver construindo um componente complexo, pode ser necessário adicionar suporte de teclado adicional além do foco. Considere o elemento de select
É focalizável e você pode usar as teclas de seta para expor funcionalidades adicionais (as opções selecionáveis).
Para implementar uma funcionalidade semelhante em seus próprios componentes, use uma técnica conhecida como "tabindex
". A movimentação do tabindex funciona definindo tabindex
como -1 para todos os filhos, exceto o atualmente ativo. O componente então usa um ouvinte de evento de teclado para determinar qual tecla o usuário pressionou.
Quando isso acontece, o componente define o tabindex
do filho focado anteriormente como -1, define o tabindex
do filho a ser focado como 0 e chama o focus()
nele.
Antes
<div role="toolbar">
<button tabindex="-1">Desfazer</div>
<button tabindex="0">Refazer</div>
<button tabindex="-1">Cortar</div>
</div>
Depois
<div role="toolbar">
<button tabindex="-1">Desfazer</div>
<button tabindex="-1">Refazer</div>
<button tabindex="0">Cortar</div>
</div>
This HTML renders a modal dialog:
<div role="dialog" aria-labelledby="dialog-header">
<button aria-label="Close"></button>
<h2 id="dialog-header">
Do you want to allow notifications from this website?
</h2>
<button>No</button>
<button>Yes</button>
</div>
What is the tab order for the elements in the sample?
- The Close button
- The No button
- The Yes button
Only the <button>
elements are included in the tab order because they're the only standardized HTML form elements. To insert other elements into the tab order, you would add a tabindex
attribute.
<section tabindex="-1">
<h2>Cat facts</h2>
<ul>
<li>A group of cats is called a <a href="https://m-w.com/dictionary/clowder">clowder</a>.</li>
<li>Most cats are <a href="https://www.catfacts.org/catnip.html"> unaffected by catnip</a>.</li>
</ul>
</section>
Which elements from the sample are included in the tab order?
Only the <a>
elements are included in the tab order.
The <section>
element is not in the tab order because it has a negative tabindex
value. (It can, however, be focused using the focus()
method.) The tabindex
value for the <section>
element doesn't affect its children.
This HTML renders a popup menu followed by a search input:
<div role="menu" tabindex="0">
<a role="menuitem" href="/learn/" tabindex="-1">Learn</a>
<a role="menuitem" href="/measure/" tabindex="-1">Measure</a>
<a role="menuitem" href="/blog/" tabindex="-1">Blog</a>
<a role="menuitem" href="/about/" tabindex="-1">About</a>
</div>
<input tabindex="1" type="text" role="search" aria-label="Search" placeholder="Search">
Which element in the sample comes first in the tab order?
The Search text input comes first in the tab order. Because it has a tabindex
greater than zero, it jumps to the front of the tab order.
(This behavior is likely to cause confusion if the menu is positioned on the page before the search input. This is an example of why having a tabindex
value greater than zero is considered an anti-pattern.)
This HTML renders a custom radio group, which should have a roving tabindex
. (To keep things simpler, ignore the aria-*
attributes for now.)
<div role="radiogroup" aria-labelledby="breed-header">
<h3 id="breed-header">Your cat's breed</h3>
<div role="radio" aria-checked="false" tabindex="0">Persian</div>
<div role="radio" aria-checked="false" tabindex="-1">Bengal</div>
<div role="radio" aria-checked="false" tabindex="-1">Maine Coon</div>
</div>
When a role="radio"
element is focused, what should happen when a user presses the Right
arrow key?
- Change the
tabindex
values for all radio elements in the group to -1. - If there's a radio element after the one that's focused, set its
tabindex
value to 0. - If there's no radio element after the one that's focused, set the
tabindex
value of the first radio element in the group to 0. - Focus the radio element that now has a
tabindex
of 0.
That's a lot—and it doesn't even include ARIA attributes! This is an example of why it's easier to use built-in elements with built-in keyboard behavior whenever you can.
Receitas de acesso ao teclado #
Se você não tiver certeza de qual nível de suporte de teclado seus componentes personalizados podem precisar, consulte ARIA Authoring Practices 1.1 . Este guia prático lista padrões comuns de IU e identifica para quais teclas seus componentes devem ter suporte.