Javascript - 如何使用键盘箭头键更改列表中链接的焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21674145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - How to change focus on links in a list with keyboard arrow keys
提问by HoffZ
I'm able to change focus when the links are not wrapped in other elements.
当链接未包含在其他元素中时,我可以更改焦点。
This works:
这有效:
HTML
HTML
<a id="first" href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
JS (with jQuery)
JS(使用 jQuery)
$(document).keydown(
function(e)
{
// Down key
if (e.keyCode == 40) {
$(".move:focus").next().focus();
}
// Up key
if (e.keyCode == 38) {
$(".move:focus").prev().focus();
}
}
);
But how do I achieve the same thing when the links are inside a list for example? Like this
但是,例如,当链接位于列表中时,我如何实现相同的目标?像这样
<ul>
<li>
<a id="first" href="#" class='move'>Link</a>
</li>
<li>
<a href="#" class='move'>Link</a>
</li>
<li>
<a href="#" class='move'>Link</a>
</li>
</ul>
回答by Anton
You can use .closest() to find the parent element then use .next() to get the next li, then use .find() to get the next .move
您可以使用 .closest() 查找父元素,然后使用 .next() 获取下一个 li,然后使用 .find() 获取下一个 .move
if (e.keyCode == 40) {
$(".move:focus").closest('li').next().find('a.move').focus();
}
// Up key
if (e.keyCode == 38) {
$(".move:focus").closest('li').prev().find('a.move').focus();
}
回答by schnill
if (e.keyCode == 40) {
$(".move:focus").parent().next().find('a').focus();
}
if (e.keyCode == 38) {
$(".move:focus").parent().prev().find('a').focus();
}
回答by dfsq
If you happen to want your focus to cycle when reaching the end of the list, you can do something like this:
如果你碰巧希望你的注意力在到达列表末尾时循环,你可以这样做:
var $li = $('li'),
$move = $(".move").click(function () {
this.focus();
});
$(document).keydown(function(e) {
if (e.keyCode == 40 || e.keyCode == 38) {
var inc = e.keyCode == 40 ? 1 : -1,
move = $move.filter(":focus").parent('li').index() + inc;
$li.eq(move % $li.length).find('.move').focus();
}
});
$move.filter(':first').focus();