2016-12-08 46 views
0

我有一個簡單ul菜單如何製作簡單的導航菜單鍵盤?

<ul role="menu" aria-label="menu"> 
    <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 1</a></li> 
    <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 2</a></li> 
    <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 3</a></li> 
    <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 4</a></li> 
</ul> 

我可以用了標籤,並向下標籤+ Shift導航。但如何使用鍵盤箭頭訪問它,以便用戶可以上下導航?

+1

小心,加入'角色= menu'你是在告訴用戶他/她可以期待它的行爲像一個操作系統菜單。您還*有*使其可以通過鍵盤訪問,並且應遵循[WAI-ARIA編寫實踐1.1菜單]中概述的模式(https://www.w3.org/TR/wai-aria-practices-1.1/#菜單)。 – aardrian

回答

1

在這裏與您的代碼工作的例子: http://plnkr.co/edit/UeUEIvO4hKzsdlhSTdNg?p=preview

<body> 
    <ul role="menu" aria-label="menu"> 
     <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 1</a></li> 
     <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 2</a></li> 
     <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 3</a></li> 
     <li role="menuitem" tabindex="0" ><a target="_blank" href="http://www.google.com">item 4</a></li> 
    </ul> 
</body> 


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

<script> 
$(document).keydown(
    function(e) 
    {  
     //38 is the keycode for arrow up 
     if (e.keyCode == 38) { 
      //check if a li is focused, if not it focus the first one  
      if($('li').is(':focus')){ 
      $("li:focus").next().focus(); 
      } 
      else{ 
      $("li:first-child").focus(); 
      } 

     } 
     else if (e.keyCode == 40) {  
      if($('li').is(':focus')){ 
      $("li:focus").prev().focus(); 
      } 
      else{ 
      $("li:first-child").focus(); 
      } 
     } 
    } 
); 
</script> 

還有就是型動物鍵碼的列表:https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

+0

按預期工作,但我可以在沒有js的情況下執行此操作嗎?我認爲特定的角色,tabindex等可以實現相同的沒有js。我錯了嗎? –

+1

使用tabindex,您可以選擇按「tab」僅用html的元素將按哪個順序進行對焦,但是如果您想使用箭頭,則必須使用javascript – grogro

+2

只需備份您的原始意圖和@ grogro的評論:arrow用於導航菜單的鍵肯定優選爲不得不通過每個菜單選項來選項卡。 [簡單訪問做了一篇文章,並提供了一些代碼來幫助](http://simplyaccessible.com/article/arrow-key-navigation/) – Skerrvy