在项目开发中遇到需要获取触发事件元素冒泡过程的所有元素,找到一个 api event.path
上代码
target.addEventListener('click', (event) => {
const ev = window.event || event
const path = ev.path
})
从截图可以看到点击事件关于 dom 元素的完整冒泡过程。
BUT
该属性在Chrome和Opera浏览器下没问题,但是在Firefox和Safari中发现event并没有path属性。
进过查找资料发现,在浏览器新的标准里定义了composedPath可以获取
target.addEventListener('click', (event) => {
const ev = window.event || event
const path = event.path || (event.composedPath && event.composedPath())
})
想了想,如果 composedPath 也不兼容呢,就换了种兼容性更好的写法
// 获取触发元素 event事件冒泡过程所有元素
export const eventPath = (e) => {
let path = (e.composedPath && e.composedPath()) || e.path,
target = e.target
if (path != null) {
// Safari doesn't include Window, but it should.
return (path.indexOf(window) < 0) ? path.concat(window) : path
}
if (target === window) {
return [window]
}
function getParents(node, memo) {
memo = memo || []
let parentNode = node.parentNode
if (!parentNode) {
return memo
} else {
return getParents(parentNode, memo.concat(parentNode))
}
}
return [target].concat(getParents(target), window)
}