【发布时间】:2021-07-31 16:51:35
【问题描述】:
在我的应用程序中,我想知道我点击的元素(或元素的父级,或祖父母,或祖父母)是否具有某种类型(例如button),以便如果它不是我正在寻找的类型,则会触发副作用。
例如,如果我单击嵌入在 span 中的元素 svg,该元素嵌入在 button 中,则检查器函数将返回“true”,因为 svg 的祖先元素的类型为button。
到目前为止,我在isParentFocusable 函数中进行了以下检查:
private isFocusable(el: HTMLElement) {
if (!el) {
return false;
}
if (el.getAttribute('focusable')) {
return true;
}
let types = ['input', 'textarea', 'button', 'select', 'a', 'menuitem'];
return (
this.verifyRoleOrTagName(el, types) ||
this.isParentFocusable(el, types)
);
}
private verifyRoleOrTagName = (element: HTMLElement, types: string[]) => {
return (
types.includes(element.tagName.toLocaleLowerCase()) ||
types.includes(element.getAttribute('role') || '')
);
};
private isParentFocusable(el: HTMLElement, types: string[]) {
let currentElement: HTMLElement | null | undefined = el;
// The upmost level to check for the parent is set to 3;
// we don't want to check all the parents up to the body tag
const MAX_PARENT_LEVEL = 3;
for (let i = 0; i < MAX_PARENT_LEVEL && currentElement; i++) {
currentElement = currentElement.parentElement;
if (currentElement && this.verifyRoleOrTagName(currentElement, types)) {
return true;
}
}
return false;
}
是否有一种优雅的方式或已知的方法来检查单击的元素是否嵌入到某种类型的标签中? (这里,类型在types 数组中列出)。
【问题讨论】:
标签: javascript html reactjs typescript