[英]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.