Safari 点击事件 event.path 为 undefined不存在

场景:

业务场景中需要获取到触发事件元素冒泡过程的所有元素,因此使用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的某个组件单独使用,因此我采用方案三实现解决。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值