如何使用键盘在元素中导航<ul> <li>



可能重复:
使用jquery 的菜单键盘导航

我使用<ul> <li>标签创建了一个菜单,并在用户按下文本框中的Enter键时将其显示给用户。他可以使用鼠标选择菜单中的项目(在菜单中导航(,但我也想允许他使用键盘的上/下按钮从该菜单中选择项目。

使用jQuery或CSS有什么方法可以做到这一点吗?

我的菜单有以下结构:

<div class="services">
  <div class="items">
    <ul>                           
        <li class="mail-icon"><a href="#" id="mail"><?php echo $langmsg['mail']; ?></a></li>
        <li class="forum-icon"><a href="#" id="forum"><?php echo $langmsg['forum']; ?></a></li>
        <li class="chat-icon"><a href="#" id="chat"><?php echo $langmsg['chat']; ?></a></li>
    </ul>
  </div>
</div>

注意:<li>元素也有背景图像。

工作jsFiddle

以下是如何处理循环选择:

if (e.keyCode == 38) { // up
    var selected = $(".selected");
    $(".services li").removeClass("selected");
    // if there is no element before the selected one, we select the last one
    if (selected.prev().length == 0) {
        selected.siblings().last().addClass("selected");
    } else { // otherwise we just select the next one
        selected.prev().addClass("selected");
    }
}

css:

.services li.selected {
    background-color: grey;   
}

这已经是可能的了,只需要HTML,用"tab"键,然后用"Enter"键。您可以将CSS样式a:hover乘以a:focus,这将突出显示这种可能性=(

最新更新