首页 > 解决方案 > 如何使用箭头键、香草 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 新手而遗漏了一些明显的东西。任何帮助是极大的赞赏。提前致谢!!

标签: javascriptfocushtml-listsarrow-keys

解决方案


推荐阅读