How to navigate with keyboard through <ul> <li> element [duplicate]

偶尔善良 提交于 2019-12-17 22:19:52

问题


Possible Duplicate:
KeyBoard Navigation for menu using jquery

I created a menu using <ul> <li> tags and showing it to the user when he presses Enter key 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.

Is it any way to do that using jQuery or 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.


回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/7308378/how-to-navigate-with-keyboard-through-ul-li-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!