[英]Keyboard navigation (up/down) link issue
我正在尝试让我的应用程序支持上/下箭头以及无序列表中的链接。
我正在复制https://jsfiddle.net/cse_tushar/5LM4R/ ,这几乎可以满足我的需求。 但是,我需要能够按Enter键并浏览重点链接。
我的无序列表如下所示:
<ul>
<li><a href="#">First Link</a></li>
<li><a href="#">Second Link</a></li>
<li><a href="#">Third Link</a></li>
</ul>
我的jQuery看起来像(仅到目前为止的向下箭头):
$(document).keyup(function(e) {
var focused_li, next;
if (e.which === 40) { // Down arrow
focused_li;
if (focused_li) {
alert("FOCUSED"); // NOT ALERTING
focused_li.find("a").focusout();
next = focused_li.next();
if (next.length > 0) {
return console.log("there is a next");
} else {
return console.log("there is no next");
}
} else {
focused_li = $("ul li").eq(0);
focused_li.find("a").focus()
}
} else if (e.which === 38) { // Up arrow
} else {
}
});
这是一个JSFiddle: https ://jsfiddle.net/p48fkw0v/
目前,它并没有在警告我有alert("FOCUSED")
并且我无法摆脱这个问题。
我真的不知道您对“ focused_li”的追求是什么,但是我想出了一个不同的解决方案。
此循环遍历您的列表,以检查哪个元素被关注并相应地关注下一个元素
新的JS代码:
$(document).keyup(function(e) {
if (e.which === 40) {
focus = false
links = $('a') //feel free to add more links it'll still work
for (var i = 0; i < links.length; i++) {
if (links[i] === (document.activeElement)) {
focus = true;
if (links[i+1] === undefined) {
console.log("last element") //reached last link
} else {
links[i+1].focus(); //focuses next link if available
}
break;
}
}
if (!focus) {
links[0].focus() //if none of the links is focused, the first one gets focused
}
} else if (e.which === 38) {
//adapt the above code to links[i-1]
} else {
}
});
这是JSfiddle:
https://jsfiddle.net/90jso3cq/
回答您有关输入触发链接的问题部分,只要您具有有效的链接,该部分就会自动发生
编辑
代码获取类“链接”的所有元素, 有时它们不按顺序排列
这是新的HTML
<ul>
<li><a id="link_1"class="link" href="#">First Link</a></li>
<li><a id="link_2"class="link" href="#">Second Link</a></li>
<li><a id="link_3"class="link" href="#">Third Link</a></li>
<ul>
和新的JS
if (e.which === 40) {
focus = false
links = $('.link') //feel free to add more links itll still work
for (var i = 0; i < links.length; i++) {
if (links[i] === (document.activeElement)) {
focus = true;
if (links[i+1] === undefined) {
console.log("last element") //reached last link
} else {
console.log(document.getElementById("link_" + (i + 2)))
document.getElementById("link_" + (i + 2)).focus(); //focuses next link if available
}
break;
}
}
if (!focus) {
document.getElementById("link_1").focus() //if none of the links is focused, the first one gets focused
}
} else if (e.which === 38) {
//adapt the above code to links[i-1]
} else {
}
});
最后但并非最不重要的是新提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.