![](/img/trans.png)
[英]Select li element with arrow keys (up and down) using Javascript (jQuery)
[英]Using arrow keys to select child li element of list
我正在嘗試建立一個帶有子菜單的菜單,這些菜單都可以通過鍵盤進行導航。 本質上,我有一個無序列表,每個列表項下面都有另一個無序列表。 我可以像這樣瀏覽我的頂級列表:
var li = $('li.tile');
var liSelected;
$(window).keydown(function(e) {
if(e.which === 40) {
if(liSelected) { // just a boolean variable at this point?
liSelected.removeClass('selected');
next = liSelected.next();
if(next.length > 0) {
liSelected = next.addClass('selected');
} else {
liSelected = li.first().addClass('selected');
}
} else {
liSelected = li.first().addClass('selected');
}
} else if(e.which === 38) {
if(liSelected) {
liSelected.removeClass('selected');
next = liSelected.prev();
if(next.length > 0) {
liSelected = next.addClass('selected');
} else {
liSelected = li.last().addClass('selected'); // not properly selecting last() because of submenu items ?
}
} else {
liSelected = li.last().addClass('selected');
}
} /* begin experiment*/ else if (e.which === 13){
$(".selected").click();
}
});
然后,我嘗試在“ else if”語句之前切換到向下鍵(案例38)之前添加此代碼-
if(liSelected && ($(".subTile").is(":visible"))){
$(".selected:first-child").addClass("selectedSub");
}
我不知道為什么它不起作用。
我有兩個CSS類,菜單的每個級別一個。 “選擇”用於頂層,“ selectedSub”用於底層,它們所做的只是更改項目的背景顏色,以便用戶知道它們的位置。
我的子菜單在開始時是隱藏的,它們像這樣打開/關閉:
var acc = document.getElementsByClassName("tile");
var i;
for (i=0;i<acc.length;i++){
acc[i].addEventListener("click", function(){
this.classList.toggle("active");
var $subItem = $("ul, li", this);
this.classList.contains("active") ? $subItem.show() : $subItem.hide() ;
})
}
我對代碼很陌生,目前迷路了。 如果有幫助的話,這是我的codepen: https ://codepen.io/kbeats/pen/YJWzeP
不建議直接操作DOM。
您可能很難放手(我們都去過那里),但是請嘗試通過以下方式重新編寫代碼。 我將分享一個偽代碼,說明應該如何做。
$('.select').removeClass('select')
arrayOfListElems = [
'#li-elem1',
'#li-elem1-1', // sub-menu of li-elem1
'#li-elem1-2', // sub-menu of li-elem1
'#li-elem2',
'#li-elem3',
]
currIndex = 0;
maxIndex = currIndex.length - 1;
if(key is pressed){
if(key is down-button){
currIndex--;
// makes sure currIndex isn't below 0
currIndex = currIndex < 0 ? 0 : currIndex;
} else if(key is up-button){
currIndex++;
// makes sure currIndex isn't below 0
currIndex = currIndex > maxIndex
? maxIndex
: currIndex;
}
currElem = arrayOfListElems[currIndex];
// do stuff with the element:
$(currElem).addClass('select')
}
這樣,您只需要以某種方式正確獲取arrayOfListElems
,無論是手動對其進行硬編碼還是以某種方式進行動態獲取,代碼都將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.