如何使用箭头键,香草JavaScript

时间:2020-03-20 03:14:12

标签: javascript focus html-lists arrow-keys

我正在创建一个小的toDo应用,我希望我的用户能够使用箭头键搜索toDo项目: ToDo app and list i would like to go through with arrows in upper right corner.

我的代码有效,但没有达到我的预期,因为它以某种随机方式跳过列表项,但是我不明白为什么会这样。

<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 {}括号中的条件保护自己免受其侵扰,所以我教: error in question

这让我发疯了,因为从逻辑上讲一切看起来都不错,因为我不熟悉JavaScript,所以我可能遗漏了一些明显的东西。任何帮助是极大的赞赏。 预先感谢!

0 个答案:

没有答案