admin管理员组文章数量:1291767
I'm able to change focus when the links are not wrapped in other elements.
This works:
HTML
<a id="first" href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
JS (with 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();
}
}
);
Demo Fiddle
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>
I'm able to change focus when the links are not wrapped in other elements.
This works:
HTML
<a id="first" href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
JS (with 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();
}
}
);
Demo Fiddle
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>
Share
Improve this question
asked Feb 10, 2014 at 10:06
HoffZHoffZ
7,7296 gold badges39 silver badges40 bronze badges
3 Answers
Reset to default 5You can use .closest() to find the parent element then use .next() to get the next li, then use .find() to get the next .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();
}
DEMO
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();
Demo: http://jsfiddle/WWQPR/5/
本文标签: jqueryJavascriptHow to change focus on links in a list with keyboard arrow keysStack Overflow
版权声明:本文标题:jquery - Javascript - How to change focus on links in a list with keyboard arrow keys - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741541790a2384363.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论