KeyBoard Navigation for menu using jquery

2019-01-25 22:11发布

问题:

I am trying to add keyboard navigation to Menu(ul li based ) , i have bound the keydown event to menu (or should i bind keydown to the document ?)

the handler function used is given below

 KeyDown: function(e) {        

    var toFocus = false;


                  if (e.keyCode == 38) {
         toFocus = $((e.target/* li */).next()[0]);
      }
                          if (e.keyCode == 40) {
         toFocus = $((e.target).next()[1]);
      }
    if (toFocus) {
        $(e.target).attr('tabIndex', '-1');
        $(toFocus).attr('tabIndex', '0');
        toFocus.focus();
        return false;
        }
        }

here i get e.target as html instead of li ?

can u suggest any other way to add keyboard navigation ?

回答1:

Try to use custom attribute to hold the tabid for up and down.

...KeyDown: function(e) {
    var Direction;
    if (e.keyCode == 38)
         Direction = "toUp";
    else Direction = "toDown";

    var Focus = $("li[tabid=\""$(e.target.id).attr(Direction)"\"]");
    Focus.focus();
}

---

<li ... tabid="1" toUp="-1" toDown= "2" />
<li ... tabid="2" toUp= "1" toDown= "3" />
<li ... tabid="3" toUp= "2" toDown= "4" />
<li ... tabid="4" toUp= "3" toDown="-1" />

The above code is just to show the idea, it is late now and I didn't have time to test it. So please don't vote me down for not working.

Hope that helps



回答2:

I just wonder if, instead of doing this by your self, why not using an already existing plugin?

jQuery Keyboard Navigation

demo page here

my demo: just to add a demo page of an example



回答3:

HTML

<body>
    <input type="text" id="target-box" >
    <ul class="list">
        <li class="selected">Hello</li>
        <li>World</li>
    </ul>
</body>

jQuery

$(document).on('focus','#target-box', function() {
    var target_box = $(this);

    $(document).on('keyup', function(e) {

        if(e.which == 38){ // up arrow
            var selected_item = $('.selected');
            if(typeof selected_item.prev()[0] !== 'undefined') {
                selected_item.prev().addClass('selected');
                selected_item.removeClass('selected');
            }
        } else if (e.which == 40) { // down arrow
            var selected_item = $('.selected');
            if (typeof selected_item.next()[0] !== 'undefined') {
                selected_item.next().addClass('selected');
                selected_item.removeClass('selected');
            }
        }

        if (e.keyCode == 13) { // enter
            target_box.val($('.selected').html());
        }
    });
});

CSS

.selected {
    width : 50px;
    background-color: gray;
}