[英]Javascript - How to change focus on links in a list with keyboard arrow keys
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>
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();
}
if (e.keyCode == 40) {
$(".move:focus").parent().next().find('a').focus();
}
if (e.keyCode == 38) {
$(".move:focus").parent().prev().find('a').focus();
}
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.