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



我有一个数据网格,在右箭头键上,它需要检查它在标头中是否有最后一个子项,以及在keydown上是否有应用于它的类focus-visible。我能够找到最后一个具有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链接

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

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

最新更新