【问题标题】:How to navigate with keyboard through <ul> <li> element [duplicate]如何通过 <ul> <li> 元素使用键盘导航[重复]
【发布时间】:2011-11-10 14:58:56
【问题描述】:

可能重复:
KeyBoard Navigation for menu using jquery

我使用&lt;ul&gt; &lt;li&gt; 标签创建了一个菜单,并在用户按下文本框中的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>

注意:&lt;li&gt; 元素也有背景图片。

【问题讨论】:

标签: jquery html css navigation contextmenu


【解决方案1】:

Working 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;   
}

【讨论】:

  • 没有完全使用你的代码,但对我帮助很大。谢谢:)
  • 如果我们有滚动条,它将无法工作。但总的来说是一个很好的例子
【解决方案2】:

这已经是可能的了,只需使用 HTML,使用“tab”键,然后使用“Enter”键。您可以将您的 CSS 样式 a:hover 加倍 a:focus,这将突出这种可能性 =)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2016-11-22
    • 2012-11-26
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多