javascript - 如何使用箭头键、香草 JavaScript 将焦点转移到列表项上
问题描述
我正在创建一个小型 toDo 应用程序,我希望我的用户能够使用箭头键搜索 toDo 项目: ToDo 应用程序和列表我想用右上角的箭头浏览。
我的代码工作但不是我想要的,因为它以某种随机方式跳过列表项,但我不明白为什么会这样。
<div class="col-md-6 align-self-center">
<input type="text" class="form-control" id="filter" placeholder="Search Items...">
<ul id="filter-ul">
</ul>
</div>
这是我有问题的html代码,只是我的搜索查询的输入文本字段和它下面的ul。但我认为我的 JS 代码有问题:
let filter = document.getElementById("filter");
filter.addEventListener("keyup", navigateThroughList);
function navigateThroughList() {
let firstItem = filterList.firstElementChild;
// firstItem.focus();
document.addEventListener("keydown", function(e) {
switch (e.key) {
case "ArrowUp":
if (document.activeElement == (filter || firstItem)) {
filterList.lastElementChild.focus();
} else {
document.activeElement.previousSibling.focus();
}
break;
case "ArrowDown":
if (document.activeElement == filter) {
firstItem.focus();
} else {
if(document.activeElement.nextSibling==null){
firstItem.focus();
}
document.activeElement.nextSibling.focus();
}
break;
}
});
}
正如我从我的几个错误中了解到的那样,这与我的输入字段没有兄弟元素有关,但我用 if{} 括号中的条件保护自己免受它的影响,或者我教过: 有问题的错误
这让我发疯,因为从逻辑上看一切都很好,我可能因为我是 JavaScript 新手而遗漏了一些明显的东西。任何帮助是极大的赞赏。提前致谢!!
解决方案
推荐阅读
- r - 替换不完全是 10 位的电话号码
- r - 仅绘制平滑线?
- angular - 如何在 Mat-table angular 5 中设置序列号
- annotations - 如何识别itext中的“回复”注释
- php - 如何在 jquery 脚本中嵌入 PHP?
- jquery - 如果我选择 1 月作为月份,2018 年作为年份,那么只显示 2018 年 1 月的完整日历
- postgresql - 从链接字符串中提取变量值
- php - Paytabs 支付网关 Api 无法正常工作
- node.js - 找不到模块'dialogflow-fulfillment'
- android - 如何在 Android.MK 文件中使用 -assumenosideeffects 标志启用 proguard