首页 > 解决方案 > 查找最后一个孩子是否在 keydown 上有特定的类

问题描述

我有一个在右箭头键上的数据网格,它需要检查它是否在标题中具有最后一个孩子,并且最后一个孩子focus-visible在 keydown 上应用了类。我可以使用 找到最后一个子元素和活动元素,但是当用户点击箭头键将焦点设置在最后一个子元素上时focus-visible,我的逻辑发现最后一个子元素存在问题。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

标签: javascriptag-gridweb-accessibility

解决方案


我发现为最后一个标题元素设置一个布尔值并切换用户是否在最后一个元素上允许用户在焦点设置到正文单元格之前导航到末尾:

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;
    }
  }
}

推荐阅读