场景:
业务场景中需要获取到触发事件元素冒泡过程的所有元素,因此使用event.path属性。
然而测试中发现在 Safari 的点击事件中,event.path 属性不存在。
资料:
在一些社区表示,IE11 和 Legacy Edge(v44 或更早版本,在从 v79 开始的 Chromium
更新之前)都不支持path或composedPath。火狐支持composedPath。Chrome 支持path(这是 Google
的最初想法)和composedPath。根据 MDN的composedPath描述,截至 2021 年 8 月,除 IE11
外,所有主要浏览器的最新版本都支持该属性。
此处查看:MDN的composedPath介绍
解决方案:
方案1
网上很多资料显示e.composedPath()方法能支持safari,类似如下:
function returnEventPath(e) {
return e.path || (e.composedPath && e.composedPath()) || ''
}
然而实践发现获取到的路径为[],即空数组。
(这里试了原生js通过getElementById获取元素是可行的,但是react中的点击事件不行)
方案2
重写全局的event对象中的composedPath方法:
// Event.composedPath
(function(e, d, w) {
if(!e.composedPath) {
e.composedPath = function() {
if (this.path) {
return this.path;
}
var target = this.target;
this.path = [];
while (target.parentNode !== null) {
this.path.push(target);
target = target.parentNode;
}
this.path.push(d, w);
return this.path;
}
}
})(Event.prototype, document, window);
方案3
函数实现composedPath方法:
const composedPath = e => {
if (e.path) {
return e.path;
}
let target = e.target;
e.path = [];
while (target.parentNode !== null) {
e.path.push(target);
target = target.parentNode;
}
e.path.push(document, window);
return e.path;
};
这里因为是react的某个组件单独使用,因此我采用方案三实现解决。