FireFox和Safari兼容eventpath

在项目开发中遇到需要获取触发事件元素冒泡过程的所有元素,在Chrome中可以通过event.path获取。

element.onClick(event) {
  const ev = window.event || event;
  const path = ev.path;
}

该属性在Chrome和Opera浏览器下没问题,但是在Firefox和Safari中发现event并没有path属性。 进过查找资料发现,在浏览器新的标准里定义的composedPath可以获取

element.onClick(event) {
  const ev = window.event || event;
  const path = event.path || (event.composedPath && event.composedPath());
  console.log(path)  //[button#btn, div, body, html, document, Window]
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理