Skip to content
Sobre Blog Aprender Explorar padrões Case studies
Nesta página
  • Verifique se seus controles são acessíveis pelo teclado
  • Insira um elemento na ordem das guias
  • Remova um elemento da ordem de tabulação
  • Evite tabindex > 0
  • Crie componentes acessíveis com "roving tabindex"
  • Receitas de acesso ao teclado

Controle o foco com tabindex

Nov 18, 2018
Available in: English, Español, Русский, 中文 e 한국어
Appears in: Acessível a todos
Rob Dodson
Rob Dodson
TwitterGitHubGlitchHomepage
Nesta página
  • Verifique se seus controles são acessíveis pelo teclado
  • Insira um elemento na ordem das guias
  • Remova um elemento da ordem de tabulação
  • Evite tabindex > 0
  • Crie componentes acessíveis com "roving tabindex"
  • Receitas de acesso ao teclado

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.

Sempre que possível, use um elemento HTML integrado em vez de construir sua própria versão personalizada. <button>. Por exemplo, é muito fácil de estilizar e ele já tem suporte completo para teclado. Isso evitará que você precise gerenciar tabindex ou adicionar semântica com ARIA.

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.

Aviso

Se você não vir um indicador de foco, ele pode estar oculto pelo seu CSS. Verifique se há estilos que mencionam :focus { outline: none; }. Você pode aprender como consertar isso em nosso guia sobre o foco do estilo.

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.

Cuidado

O inert é experimental e pode não funcionar como esperado em todos os casos. Teste cuidadosamente antes de usar na produção.

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>
Tem a curiosidade de saber para que servem esses atributos role=""? Eles permitem que você altere a semântica de um elemento para que seja anunciado corretamente por um leitor de tela. Você pode aprender mais sobre eles em nosso guia noções básicas do leitor de tela.
Test your knowledge of tab order

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?

  1. The Close button
  2. The No button
  3. 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.

Last updated: Nov 18, 2018 — Improve article
Return to all articles
Compartilhar
assinar

Contribute

  • Registrar um bug
  • Visualizar código-fonte

Conteúdo relacionado

  • developer.chrome.com
  • Atualizações do Chrome
  • Estudos de caso
  • Podcasts
  • Shows

Conectar

  • Twitter
  • YouTube
  • Google Developers
  • Chrome
  • Firebase
  • Google Cloud Platform
  • Todos os produtos
  • Termos e privacidade
  • Diretrizes da comunidade

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies.