繁体   English   中英

KeyBoard使用jquery导航菜单

[英]KeyBoard Navigation for menu using jquery

我正在尝试将键盘导航添加到菜单(基于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?

你可以建议任何其他方式添加键盘导航?

我只是想知道为什么不使用现有的插件而不是自己这样做?

jQuery键盘导航

这里是演示页面

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

尝试使用自定义属性来保持tabid for up和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" />

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

希望有所帮助

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM