使用jQuery进行键导航

使用jQuery进行键导航,jquery,Jquery,我知道有很多关于使用键盘事件导航的问题。然而,由于我想了解一切,而不仅仅是复制粘贴的东西,我找不到关于这个主题的任何好的解释或教程 这是我到目前为止得到的,它适用于左箭头和右箭头。但是如果有人能给我指出正确的方向,如何使它也适用于上下箭头,我将非常高兴!也许这不是解决这个问题的最好办法,但首先我只想了解基本原理 <a class="link" href="#">Link 1</a> <a class="link" href="#">Link 2</a&g

我知道有很多关于使用键盘事件导航的问题。然而,由于我想了解一切,而不仅仅是复制粘贴的东西,我找不到关于这个主题的任何好的解释或教程

这是我到目前为止得到的,它适用于左箭头和右箭头。但是如果有人能给我指出正确的方向,如何使它也适用于上下箭头,我将非常高兴!也许这不是解决这个问题的最好办法,但首先我只想了解基本原理

<a class="link" href="#">Link 1</a>
<a class="link" href="#">Link 2</a>
<a class="link" href="#">Link 3</a>
<a class="link" href="#">Link 4</a>
<a class="link" href="#">Link 5</a>
<br />
<a class="link" href="#">Link 1</a>
<a class="link" href="#">Link 2</a>
<a class="link" href="#">Link 3</a>
<a class="link" href="#">Link 4</a>
<a class="link" href="#">Link 5</a>



if (e.which == 39) {      
        $("a:focus").next().focus();

    }
    if (e.which == 37) {      
        $("a:focus").prev().focus();

    }


如果(e.which==39){ $(“a:focus”).next().focus(); } 如果(e.which==37){ $(“a:focus”).prev().focus(); }
在使用键绑定时,我喜欢使用此模块,这样可以大大降低复杂性,并且代码更易于阅读/维护


我知道你想从一行跳到另一行


尝试在jQuery中使用
:nth-child()
选择器,这样您就可以选择所需的任何元素(在本例中为上面的元素)。

我编写了一个将链接拆分为两个div的示例:

<div id="menu1">
    <a class="link" href="#">Link 1</a>
    <a class="link" href="#">Link 2</a>
    <a class="link" href="#">Link 3</a>
    <a class="link" href="#">Link 4</a>
    <a class="link" href="#">Link 5</a>
</div>
<div id="menu2">
    <a class="link" href="#">Link 1</a>
    <a class="link" href="#">Link 2</a>
    <a class="link" href="#">Link 3</a>
    <a class="link" href="#">Link 4</a>
    <a class="link" href="#">Link 5</a>
</div>

编辑

保持相同的索引

// move to first link on previous div
else if (e.which == 38) {
    var index = current.index() + 1;
    current.parent().prev().find('a:nth-child(' + index + ')').focus();
}
// move to first link on next div
else if (e.which == 40) {
    var index = current.index() + 1;
    current.parent().next().find('a:nth-child(' + index + ')').focus();
}

您可能正在寻找不同的钥匙代码。向上/向下分别为38和40。要了解更多信息,请查看我知道键代码,我知道如何在向上键时发出警报,问题是我不知道如何使用向上键或向下键在div之间移动谢谢你的小提琴,但我想实现的是根据当前位置上下移动光标。与left和right(prev,next)完全相同,但用于向上和向下。看:啊,谢谢你!我试过第n个孩子,但没有成功!谢谢你的回答!
// move to first link on previous div
else if (e.which == 38) {
    var index = current.index() + 1;
    current.parent().prev().find('a:nth-child(' + index + ')').focus();
}
// move to first link on next div
else if (e.which == 40) {
    var index = current.index() + 1;
    current.parent().next().find('a:nth-child(' + index + ')').focus();
}