3

我正在尝试将键盘导航添加到菜单(基于 ul li),我已将 keydown 事件绑定到菜单(或者我应该将 keydown 绑定到文档?)

使用的处理函数如下所示

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

在这里我得到e.target 作为 html而不是 li ?

你能建议任何其他方式来添加键盘导航吗?

4

3 回答 3

1

我只是想知道,与其自己做这件事,为什么不使用已经存在的插件?

jQuery 键盘导航

演示页面在这里

我的演示:只是添加一个示例的演示页面

于 2009-09-11T06:06:50.263 回答
1

尝试使用自定义属性来保持 tabid 上下。

...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" />

上面的代码只是为了展示想法,现在已经很晚了,我没有时间测试它。所以请不要因为我不工作而投票给我。

希望有帮助

于 2009-09-11T06:19:40.737 回答
0

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;
}
于 2016-04-11T12:55:55.673 回答