代码之家  ›  专栏  ›  技术社区  ›  Matt

查找最后一个子级是否在keydown上有特定的类

  •  0
  • Matt  · 技术社区  · 7 年前

    focus-visible 焦点可见 ,但我的逻辑发现最后一个孩子 当用户点击箭头键设置最后一个子对象的焦点时。

    到目前为止,这是我的逻辑,但不确定我在检查最后一个孩子的班级时出错的地方:

      //
      //ON ARROW RIGHT, IF FOCUS IS ON LAST HEADER, SET FOCUS TO FIRST BODY CELL
      //
      if(e.key === "ArrowRight") {
        let headerId = document.activeElement.parentElement.parentElement.getAttribute("col-id");
        //Get last child
        const headerCell = document.querySelector('.ag-header-cell:last-child').children[1].children[1];
        //focus visible class on nav element
        const hasFocusVisible = document.activeElement.classList.contains('focus-visible');
        console.log("last child: ", headerCell);
        console.log("has focus visible: ", hasFocusVisible);
        if(headerCell.classList.contains('focus-visible')) {
          //if headerCell and hasFocusVisible, set focus to first cell in body
          document.querySelector('.ag-cell').focus();
        }
      }
    

    发行现状: Plnkr Link

    1 回复  |  直到 7 年前
        1
  •  0
  •   Matt    7 年前

    我发现为最后一个header元素设置一个布尔值,并在用户位于最后一个元素时进行切换,这样用户就可以在焦点设置为body单元格之前导航到末尾:

    let lastHeaderCell = false;
    document.addEventListener("keydown", function(e) {
      if(e.key === "ArrowRight") {
        let headerId = document.activeElement.parentElement.parentElement.getAttribute("col-id");
        const headerCell = document.querySelector('.ag-header-cell:last-child').children[1].children[1];
        const hasFocusVisible = document.activeElement.classList.contains('focus-visible');
        if(lastHeaderCell === true) {
          document.querySelector('.ag-cell').focus();
          lastHeaderCell = false;
        }
        else if(headerCell.classList.contains('focus-visible')) {
          lastHeaderCell = true;
        }
      }
    }