输入框聚焦时如何向上查找DOM层级中首个带指定class的元素
解决方案
你不需要手动遍历element.path,DOM原生提供了Element.closest()方法可以直接实现需求:该方法会从当前元素出发,沿DOM树向上递归查询所有祖先节点,返回第一个匹配指定CSS选择器的元素,完全符合你「向上遍历直到找到带note类元素」的诉求。
完整实现代码
// 监听聚焦事件设置高亮 document.addEventListener('focusin', (event) => { const targetNote = event.target.closest('.note') if (targetNote) targetNote.style.backgroundColor = 'yellow' }) // 可选:监听失焦事件清除高亮,避免多个note被同时标记 document.addEventListener('focusout', (event) => { const targetNote = event.target.closest('.note') if (targetNote) targetNote.style.backgroundColor = '' })
兼容旧浏览器的兜底方案
如果需要兼容IE11及更早版本不支持closest的场景,可以手动实现向上遍历逻辑:
function getClosestNote(el) { while (el && el.tagName !== 'BODY') { if (el.classList?.contains('note')) return el el = el.parentElement } return null } // 调用替换即可 document.addEventListener('focusin', (event) => { const targetNote = getClosestNote(event.target) if (targetNote) targetNote.style.backgroundColor = 'yellow' })
内容的提问来源于stack exchange,提问作者WoJ
相关产品推荐
相关产品推荐

