event.path参数被浏览器删除,如何一劳永逸的解决

问题

2月初,Chrome(版本号109.0.5414.120)在一次升级中删除绑定点击等等部分事件中的Event.path数组参数,(Edge和其他国产chromium内核浏览器是没有变化的),官方升级记录日志记录
最早从官方issue中可获知chromium内核团队早在21年就开始认为 Event.path 属于非标准 API,某些地方已经开始删除event.path数组参数了。
且event.path是Chrome内核单独支持的属性,不在MDN的标准中。所以兼容性还是存在缺点。

解决方法

方法1(不推荐):

var composed = Event.composedPath();

MDN中有一个composedPath方法,但是根据网上的某些网友反馈也有可能返回空数组(暂未找到原因)。

方法2(推荐):

自己仿照 composedPath() 方法原理,将当前所有的冒泡一层一层 parentNode 元素收集起来。在push到数组里面。

const composedPath = (e: Record<string, any>) => {
  // 当前有直接return
  let pathArr = e.path || (e.composedPath && e.composedPath()); // 优先判断 Event.composedPath() 方法是否为空数组
  if ((pathArr || []).length) { 
    return pathArr;
  }
  // 不存在则遍历target节点
  let target = e.target
  e.path = []
  while (target.parentNode !== null) {
    e.path.push(target)
    target = target.parentNode
  }
  // 最后在add进去 document 与 window对象
  e.path.push(document, window)
  return e.path;
};
posted @ 2023-02-12 01:39  天渺工作室  阅读(190)  评论(0编辑  收藏  举报