jQuery 如何通过 <ul> <li> 元素使用键盘导航

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7308378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:40:55  来源:igfitidea点击:

How to navigate with keyboard through <ul> <li> element

jqueryhtmlcssnavigationcontextmenu

提问by Bakhtiyor

Possible Duplicate:
KeyBoard Navigation for menu using jquery

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

I created a menu using <ul> <li>tags and showing it to the user when he presses Enterkey in the textbox. He can select items of the menu (navigate in menu) using mouse but I want also to allow him to select items from that menu using up/dow buttons of the keyboard for example.

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

Is it any way to do that using jQuery or CSS?

有没有办法使用 jQuery 或 CSS 做到这一点?

My menu has following structure:

我的菜单具有以下结构:

<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>

Note: <li>element has a background image also.

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

回答by Benjamin Crouzier

Working jsFiddle

工作 jsFiddle

Here is how to handle circular selection:

以下是处理循环选择的方法:

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:

css:

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

回答by Lamecarlate

It's already possible, just with HTML, with "tab" key, then "Enter" key . You can double your CSS style a:hoverby a a:focus, which will highlight this possibility =)

已经可以了,只用 HTML,用“tab”键,然后用“Enter”键。您可以双击你的CSS样式a:hovera:focus,将突出这种可能性=)