javascript - 查找最后一个孩子是否在 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
解决方案
我发现为最后一个标题元素设置一个布尔值并切换用户是否在最后一个元素上允许用户在焦点设置到正文单元格之前导航到末尾:
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;
}
}
}
推荐阅读
- clojure - 解决来自 Leiningen 的 GitLab 的私有依赖项
- wordpress - 隐藏第一部分
- laravel - 如何在 laravel 中对控制器进行单元测试?
- vue.js - 具有不同元素标签的Vue3“v-is”组件
- javascript - 在 redux 工具包状态中更改数组中的特定元素
- arrays - 在列中查找值并根据条件更改结果
- python - 从数据框获取项目 A 的第一个订单与前一个订单之间的天数,前一个订单可以是项目 A 或不同的项目
- javascript - TypeError: Object (...) is not a function in react & js
- python - 不一致的通信链路故障 (10060) 错误
- html - 如何仅在css文件中设置句子中单个单词的样式而不添加额外的标签(例如span)并且没有js