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

17

可能是重复问题:
如何使用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>元素也有背景图像。


1
https://dev59.com/KEnSa4cB1Zd3GeqPM04t - Ruslan
2个回答

22

这是一个可用的 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;   
}

没有完全使用你的代码,但是对我帮助很大。谢谢 :) - Pedro Romão
如果我们有滚动条,它就无法工作。但总体来说是一个很好的例子。 - Pratap A.K

3

通过HTML,使用“tab”键,然后按“Enter”键即可完成。您可以通过a:focus来双倍增强CSS样式中的a:hover,从而突出显示这种可能性=)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接