javascript - 使用箭头键选择列表的子 li 元素
问题描述
我正在尝试构建一个带有子菜单的菜单,这些子菜单都可以通过键盘导航。本质上我有一个无序列表,每个列表项下面都有另一个无序列表。我可以像这样浏览我的顶级列表:
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 类,一个用于菜单的每一级。'selected' 用于顶层图层,'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() ;
})
}
我对代码很陌生,目前非常迷茫。如果有帮助,这是我的代码笔: 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
正确获取,无论是手动硬编码还是以某种方式动态获取,代码都可以工作。
推荐阅读
- json - 从维基百科获取标题
- java - 如何确定在 recycelview 布局上单击了哪个卡片视图?
- svelte - 没有变化的苗条更新总是触发重新渲染
- python - 在 Django 中向特定用户显示私人内容
- system-verilog - 我无法编译 .sv 文件 (SystemVerilog)
- sql - 如何在 COPY 命令上添加文件的缺失值
- admob - 任何人都可以解释激励广告格式的具体政策
- python - 硒解析 https://myip.ms
- python - 使用随机森林进行多分类 - 如何衡量结果的“稳定性”
- pytorch - 在 Pytorch 中,当传输到 GPU 时,我收到一个错误“在 CPU 上,但应该在 GPU 上”